Skip to content

Instantly share code, notes, and snippets.

@PyBagheri
Created September 30, 2017 14:03
Show Gist options
  • Save PyBagheri/b33cdddcabd210385c2741df34378755 to your computer and use it in GitHub Desktop.
Save PyBagheri/b33cdddcabd210385c2741df34378755 to your computer and use it in GitHub Desktop.
Simple Autp learning Chat Bot
from telegram.ext import Updater, MessageHandler, Filters
import sqlite3
import random
import difflib
u = Updater('Your 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:
if update.to_dict()['message']['from']['id'] == 186294909 and update.to_dict()['message']['reply_to_message']['from']['id'] == 186294909 or update.to_dict()['message']['from']['id'] == 324469663 and update.to_dict()['message']['reply_to_message']['from']['id'] == 324469663:
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):
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, cutoff=0.68)
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