Skip to content

Instantly share code, notes, and snippets.

@PyBagheri
Created October 6, 2017 09:54
Show Gist options
  • Save PyBagheri/ca3c68c101afb605e9bc2bf5a952f624 to your computer and use it in GitHub Desktop.
Save PyBagheri/ca3c68c101afb605e9bc2bf5a952f624 to your computer and use it in GitHub Desktop.
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