Skip to content

Commit

Permalink
cleaning up a little, and added fabfile
Browse files Browse the repository at this point in the history
  • Loading branch information
MohGanji committed Dec 30, 2017
1 parent a1f3e54 commit 557db1c
Show file tree
Hide file tree
Showing 11 changed files with 202 additions and 53 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -65,3 +65,4 @@ webhook_cert.pem
webhook_pkey.pem
.vscode/
bot_url.py
*.pyc
27 changes: 27 additions & 0 deletions ConstMessages.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Constant messages and strings used in bot
"""

## CONST MESSAGES ##

START_MESSAGE = "Hi, all you need to do is add me to a group and\
then reply 'fa or فا' to any message and I will transliterate it for you.\n\
or just send me a message"

HELP_MESSAGE = "Use this bot to transliterate Finglish messages to Farsi.\n\
add this bot to your groups, and if you see any finglish message,\
reply 'fa', 'فا' to the message.\n\
\nبا این ربات می‌توانید پیام های فینگلیش را به فارسی تبدیل کنید،\
کافی است ربات را در گروه های خود اضافه کرده\
و اگر پیام فینگلیش دیدید، در پاسخ به آن بنویسید 'fa' یا 'فا'"

CONTACT_MESSAGE = "please email me :\n [email protected]"

ABOUT_MESSAGE = "من محمد فغان‌پور گنجی هستم،\n\
اطلاعات بیشتر در مورد من رو در mohganji.ir می‌تونید ببینید"

####################
print ABOUT_MESSAGE

7 changes: 7 additions & 0 deletions Consts.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
"""
Constants used in bot
"""

##### CONSTS #######
MY_ID = 117990761
####################
2 changes: 2 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
clean:
rm *.pyc
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,8 @@ Use this bot in your groups to transliterate finglish messages to farsi
- [x] add wrong word report for groups too
- [x] add word database and collect user words
- [x] add bug report feature
- [ ] send reports to myself to check if they are correct and then use corrected collection
- [x] send reports to myself to check if they are correct and then use corrected collection
- [ ] code accept and reject callback functions
- [ ] do not transliterate abbreviations, like CTO
- [ ] defallahi method
- [ ] handle irregular syntaxes
Expand Down
9 changes: 9 additions & 0 deletions States.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
"""
Bot states.
"""
###### STATES ######

IDLE = 0
REPORT = 1

####################
63 changes: 11 additions & 52 deletions bot.py
Original file line number Diff line number Diff line change
@@ -1,46 +1,21 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
Main bot logic
"""

##### IMPORTS ######
import logging
import time
import telebot
from Token import TOKEN
from mongo_auth import dbuser, dbpass
from bot_url import BOT_URL
import pymongo
from utils import *
from init import *
####################

###### STATES ######
IDLE=0
REPORT=1

####################


## CONST MESSAGES ##
START_MESSAGE = "Hi, all you need to do is add me to a group and then reply 'fa or فا' to any message and I will transliterate it for you.\n or just send me a message"
HELP_MESSAGE = "Use this bot to transliterate Finglish messages to Farsi.\n add this bot to your groups, and if you see any finglish message, reply 'fa', 'فا' to the message.\n\nبا این ربات می‌توانید پیام های فینگلیش را به فارسی تبدیل کنید، کافی است ربات را در گروه های خود اضافه کرده و اگر پیام فینگلیش دیدید، در پاسخ به آن بنویسید 'fa' یا 'فا'"
CONTACT_MESSAGE = "please email me :\n [email protected]"
ABOUT_MESSAGE = "من محمد فغان‌پور گنجی هستم،\n اطلاعات بیشتر در مورد من رو در mohganji.ir می‌تونید ببینید"

####################

##### CONSTS #######
MY_ID = 117990761
####################


## INITIALIZATION ##
bot = telebot.TeleBot(TOKEN)

logger = telebot.logger
telebot.logger.setLevel(logging.INFO)

db = pymongo.MongoClient('mongodb://%s:%[email protected]:27017/finToFa' % (dbuser, dbpass)).finToFa

####################

##### HANDLERS #####
@bot.message_handler(commands=['start'])
Expand All @@ -56,7 +31,6 @@ def initialize(message):
bot.reply_to(message,
(START_MESSAGE))


@bot.message_handler(commands=['help'])
def help_provider(message):
""" function for help command """
Expand Down Expand Up @@ -84,22 +58,6 @@ def handle_all_callbacks(callback):
# this runs a function named callback['data'], with callback as the only argument
globals()[callback.data](callback)

def create_message_markup(buttons):
""" buttons is an array of dictionaries containing text and callback data:
buttons = [{
"text": "buttonText1",
"data": "callBackData1"
},
{
"text": "buttonText2",
"data": "callBackData2"
}]
"""
markup = telebot.types.InlineKeyboardMarkup(row_width=1)
for button in buttons:
new_button = telebot.types.InlineKeyboardButton(button["text"], callback_data=button["data"])
markup.add(new_button)
return markup

@bot.message_handler(func=lambda message: True, content_types=['text'])
def handle_group_or_user(message):
Expand All @@ -115,15 +73,15 @@ def handle_group_or_user(message):
bot.send_message(message.from_user.id, "با تشکر از شما، گزارش شما با موفقیت ثبت شد.")
accept_message_buttons = [
{
"text": "accept",
"text": "",
"data": "accept"
},
{
"text": "reject",
"text": "",
"data": "reject"
}
]
accept_markup = create_message_markup(accept_message_buttons)
accept_markup = create_message_markup(accept_message_buttons, row_width=2)
accept_report_text = "New Report:" + \
"\nFinglish: " + user_reported['report']['finglish_msg'] + \
"\nFarsi: " + user_reported['report']['farsi_msg'] + \
Expand Down Expand Up @@ -179,15 +137,16 @@ def wrong(callback):
bot.answer_callback_query(callback.id, url=BOT_URL+str(finglish_msg))

def accept(callback):
bot.answer_callback_query(callback.id)
# add words to database and search from them.
bot.answer_callback_query(callback.id, text="accepted")

def reject(callback):
# delete ? record from database
bot.answer_callback_query(callback.id)

def like(callback):
pass


####################


Expand Down
54 changes: 54 additions & 0 deletions callback instance.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
# callback instance:
#{
# 'inline_message_id': None,
# 'chat_instance': u'-490179135417304710',
# 'from_user': {
# 'username': u'MohGanji',
# 'first_name': u'MoHaMMaD',
# 'last_name': None,
# 'id': 117990761,
# 'language_code': u'en-US'
# },
# 'message': {
# 'forward_from_chat': None,
# 'new_chat_photo': None,
# 'invoice': None,
# 'text': u'New Report:\nFinglish: base\nFarsi: \u0628\u0633\nCorrected: \u0628\u0633\u0647',
# 'sticker': None,
# 'successful_payment': None,
# 'pinned_message': None,
# 'delete_chat_photo': None,
# 'migrate_from_chat_id': None,
# 'new_chat_members': None,
# 'video': None,
# 'left_chat_member': None,
# 'chat': <telebot.types.Chat instance at 0x7f2f38106fc8>,
# 'group_chat_created': None,
# 'migrate_to_chat_id': None,
# 'forward_date': None,
# 'entities': None,
# 'location': None,
# 'photo': None,
# 'document': None,
# 'forward_from': None,
# 'supergroup_chat_created': None,
# 'edit_date': None,
# 'content_type': 'text',
# 'from_user': <telebot.types.User instance at 0x7f2f38106f80>,
# 'date': 1507545273,
# 'new_chat_member': None,
# 'audio': None,
# 'reply_to_message': None,
# 'venue': None,
# 'message_id': 2476,
# 'caption': None,
# 'contact': None,
# 'channel_chat_created': None,
# 'video_note': None,
# 'voice': None,
# 'new_chat_title': None
# },
# 'data': u'accept',
# 'id': u'506766463387624646',
# 'game_short_name': None
#}
41 changes: 41 additions & 0 deletions fabfile.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
"""
fabric file used for remote deploy and logging
"""

from __future__ import with_statement
from fabric.api import *

# or @hosts
env.hosts = ['[email protected]']

CODE_DIR = '/var/www/finToFaBot'


def deploy():
"""
run fab deploy to deploy updated code
"""
with cd(CODE_DIR):
run('git checkout -- .')
run('git rev-parse HEAD > ./.gitPrevHead.bak')
run('git pull')
run('pm2 reload finToFaBot')

def status():
"""
run 'fab status' to see bot status
"""
run('pm2 show finToFaBot')

def log():
"""
run 'fab log' to see bot logs.
"""
run('pm2 logs finToFaBot --lines 100')

def rollback():
"""
run 'fab rollback' to rollback to previous commit
"""
with cd(CODE_DIR):
run('git checkout `cat ./.gitPrevHead.bak`')
27 changes: 27 additions & 0 deletions init.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
bot initialization
"""

##### IMPORTS ######
import logging
import telebot
from Token import TOKEN
from mongo_auth import dbuser, dbpass
from bot_url import BOT_URL
import pymongo
from utils import *
####################

## INITIALIZATION ##

bot = telebot.TeleBot(TOKEN)

logger = telebot.logger
telebot.logger.setLevel(logging.INFO)

db = pymongo.MongoClient('mongodb://%s:%[email protected]:27017/finToFa' % (dbuser, dbpass)).finToFa

####################
21 changes: 21 additions & 0 deletions utils.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
import logging
from subprocess import (PIPE, Popen)
import telebot
from ConstMessages import *
from Consts import *
from States import *

def add_new_user(db, username, chatId):
""" add a new user to database for broadcasting."""
Expand Down Expand Up @@ -48,3 +52,20 @@ def add_report_request(db, message):
db.reports.insert_one(new_report_instance)
logging.critical("A new report record added: " + str(new_report_instance))
db.users.update({'id': message.from_user.id}, {'$set': {'state': 0}})

def create_message_markup(buttons, row_width=1):
""" buttons is an array of dictionaries containing text and callback data:
buttons = [{
"text": "buttonText1",
"data": "callBackData1"
},
{
"text": "buttonText2",
"data": "callBackData2"
}]
"""
markup = telebot.types.InlineKeyboardMarkup(row_width=row_width)
for button in buttons:
new_button = telebot.types.InlineKeyboardButton(button["text"], callback_data=button["data"])
markup.add(new_button)
return markup

0 comments on commit 557db1c

Please sign in to comment.