Skip to content

Instantly share code, notes, and snippets.

@alexey-sveshnikov
Last active February 7, 2018 20:00
Show Gist options
  • Save alexey-sveshnikov/6f57c32e8e747b1ae772673adb132535 to your computer and use it in GitHub Desktop.
Save alexey-sveshnikov/6f57c32e8e747b1ae772673adb132535 to your computer and use it in GitHub Desktop.
# Dependencies: pip install markovify python-telegram-bot
import logging
import json
import telegram
import markovify
from telegram.ext import CommandHandler, Updater, Filters
TOKEN='.........'
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO)
msg_agg = json.load(open('messages.json'))
models = {}
all_messages = []
for username, messages in msg_agg.items():
models[username] = markovify.NewlineText('\n'.join(messages))
all_messages.extend(messages)
all_model = markovify.NewlineText('\n'.join(all_messages), 2)
updater = Updater(token=TOKEN)
dispatcher = updater.dispatcher
bot = telegram.Bot(token=TOKEN)
def chat_name(update):
if update.message.chat.type == 'private':
return 'private'
else:
return update.message.chat.title
def start(bot, update):
logging.info('[%s] [%s] /start', chat_name(update), update.message.from_user.name)
bot.send_message(chat_id=update.message.chat_id, text="Hi there. Type /quote <username>")
start_handler = CommandHandler('start', start)
dispatcher.add_handler(start_handler)
def quote(bot, update, args):
logging.info('[%s] [%s] %s', chat_name(update), update.message.from_user.name, update.message.text)
username = None
if args:
username = args[0]
username = username.strip()
username = username.replace('@', '')
if username:
if not username in models:
bot.send_message(chat_id=update.message.chat_id, text='unknown user')
return
message = models[username].make_sentence(tries=100)
else:
message = all_model.make_sentence(tries=100)
if not message:
message = 'Что-то ничего не приходит в голову'
logging.info('[%s] Sending %s', chat_name(update), message)
bot.send_message(chat_id=update.message.chat_id, text=message)
quote_handler = CommandHandler('quote', quote, pass_args=True)
dispatcher.add_handler(quote_handler)
updater.start_polling()
################################
# update.py
from telethon import TelegramClient
client = TelegramClient('session_name', 'app id', 'key')
history = client.get_message_history(rt.entity, limit=10000)
msg_agg = {}
for msg in history:
text = msg.message or ''
text = text.strip()
if not text:
continue
user_history = msg_agg.setdefault(msg.sender.username, [])
user_history.append(msg.message)
print(sorted(((len(msgs), username) for username, msgs in msg_agg.items()), reverse=True))
with open('messages.json', 'w') as f:
json.dump(msg_agg, f, indent=True, ensure_ascii=False)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment