Created
October 6, 2017 09:54
-
-
Save PyBagheri/ca3c68c101afb605e9bc2bf5a952f624 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from telegram.ext import Updater, MessageHandler, Filters | |
import sqlite3 | |
import random | |
import difflib | |
u = Updater('you token here...') | |
d = u.dispatcher | |
connection = sqlite3.connect('myDatabase.db', check_same_thread=False) | |
connection.execute('CREATE TABLE IF NOT EXISTS myTbl(ID INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, QUES TEXT NOT NULL, ANSW TEXT NOT NULL)') | |
connection.commit() | |
cursor = connection.cursor() | |
def group(bot, update): | |
answer = update.message.text | |
if answer: | |
try: | |
if update.to_dict()['message']['reply_to_message']['from']['id'] != update.to_dict()['message']['from']['id']: | |
question = update.message.reply_to_message.text | |
else: | |
question = None | |
except Exception: | |
question = None | |
if answer: | |
connection.execute("INSERT INTO myTbl (QUES, ANSW) VALUES (?, ?)", (question, answer)) | |
connection.commit() | |
def private(bot, update): | |
# Two line for removing a record. or some bad words... | |
# cursor.execute('DELETE FROM myTbl WHERE ANSW=?', ('Bad word...',)) | |
# connection.commit() | |
question = update.message.text | |
if question: | |
res, tmp = [], [] | |
try: | |
result = cursor.execute('SELECT QUES FROM myTbl') | |
for i in result: | |
tmp.append(i[0]) | |
tt = difflib.get_close_matches(question, tmp) | |
for i in tt: | |
one = cursor.execute('SELECT ANSW FROM myTbl WHERE QUES=?', (i,)) | |
res.extend([u[0] for u in one]) | |
if res: | |
bot.send_message(chat_id=update.message.chat_id, text=res[random.randint(0, len(res) - 1)], reply_to_message_id=update.message.message_id) | |
except sqlite3.Error as e: | |
print(e) | |
d.add_handler(MessageHandler(Filters.group, group)) | |
d.add_handler(MessageHandler(Filters.private, private)) | |
u.start_polling() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment