Skip to content

Instantly share code, notes, and snippets.

@jowrjowr
Created January 26, 2019 17:46
Show Gist options
  • Save jowrjowr/ad9fbfd2293c9e26afd08767918b0fd9 to your computer and use it in GitHub Desktop.
Save jowrjowr/ad9fbfd2293c9e26afd08767918b0fd9 to your computer and use it in GitHub Desktop.
example use case of telethon
import common.logger as _logger
import common.request_esi
import urllib
import time
import threading
import logging
import traceback
from telethon import TelegramClient
from telethon.tl.types import UpdatesTg
from telethon.tl.types.update_short_message import UpdateShortMessage
from parser import parse_message, rus_to_en
def update_handler(object):
logger = logging.getLogger('ping_relay.telegram.update_handler')
logger.debug('new telegram object')
# this specifically processes update objects from telegram
# looking for specific kinds of update objects that indicate a direct message
if not isinstance(object, UpdateShortMessage): return
content = object.message
date = object.date
msg = 'xdeath ping (rus): {0}'.format(content)
logger.info(msg)
cover = 'xdeath'
parsed_message = parse_message(cover, content)
queue.put(parsed_message)
return
def start_telegram(discord_queue):
global queue
queue = discord_queue
# right now just xdeath
logger = logging.getLogger('ping_relay.telegram')
logger.info('starting up telegram')
forward_telegram_xdeath()
def forward_telegram_xdeath():
# set the thread name to the spy cover, for logging purposes
thread = threading.current_thread()
thread.setName('xdeath')
logger = logging.getLogger('ping_relay.telegram.xdeath')
logger.info('starting up xdeath')
# constants
session_id = 'xdeath'
api_id = xxxx
api_hash = 'xxxxx'
phone = '+xxxxx'
# construct client
try:
client = TelegramClient(session_id, api_id, api_hash)
except Exception as e:
msg = 'unable to construct telegram client: {0}'.format(e)
logger.exception(msg)
msg = '```diff' + '\n' + '- xdeath offline```'
discor_queue.put(msg)
try:
client.connect()
except Exception as e:
msg = 'unable to connect to xdeath telegram: {0}'.format(e)
logger.critical(msg)
msg = '```diff' + '\n' + '- xdeath offline```'
discor_queue.put(msg)
return
print('eeeeeeeeee')
# this will create a session file in CWD named "session_id".session
if not client.is_user_authorized():
msg = '```diff' + '\n' + '- xdeath AUTHENTICATION REQUIRED```'
queue.put(msg)
msg = 'need to reauthorize xdeath tool'
logger.warning(msg)
client.send_code_request(phone)
client.sign_in(phone, input('Enter code: '))
else:
print('aaaaaa')
msg = '```diff' + '\n' + '+ xdeath online```'
try:
queue.put(msg)
except Exception as e:
print(e)
print(msg)
# pickup the last so many dialogs (distinct groups/messages?) sent to the client
dialogs, entities = client.get_dialogs(10)
print('eeeeeeeeeentities')
# this is currently the xdeath bot, but the ordering might change? we'll see.
# seems to follow the client ordering, starting frm top down with index 0
msg = 'printing last few old xdeath pings'
logger.info(msg)
for entity in entities:
total_count, messages, senders = client.get_message_history(entity, limit=5)
for msg, sender in zip(reversed(messages), reversed(senders)):
try:
username = sender.username
content = msg.message
date = msg.date
except Exception as e:
# if it doesn't resolve, it isn't a message anyway
continue
# we don't care about non-ping messages
if not username == 'xxdeathxx_bot': continue
try:
en_content = rus_to_en(content)
except Exception as e:
print(content, e)
msg = 'previous death ping (rus): {0}'.format(content)
logger.info(msg)
msg = 'previous xdeath ping (eng): {0}'.format(en_content)
logger.info(msg)
# infinite loop to monitor for updates
logger.debug('adding update handler')
try:
client.add_update_handler(update_handler)
except Exception as e:
print(e)
tick = 0
authorized = True
while authorized:
logger.debug('xdeath life ping')
time.sleep(30)
tick += 1
authorized = client.is_user_authorized()
if authorized is False:
logger.warning('xdeath lost authorization')
# we disconnected. try to reconnect.
# redo the connection sequence
client.disconnect()
msg = '```diff' + '\n' + '- xdeath offline```'
queue.put(msg)
# reinitialize the telegram client
try:
client = TelegramClient(session_id, api_id, api_hash)
except Exception as e:
logger.critical(e)
try:
client.connect()
client.add_update_handler(new_thing)
except Exception as e:
msg = 'unable to reconnect to xdeath telegram: {0}'.format(e)
logger.critical(msg)
return
# we reconnected?
authorized = client.is_user_authorized()
else:
logger.debug('xdeath still authorized')
if tick % 120 == 0:
# every hour log that you are alive
msg = 'xdeath hourly life ping'
logger.debug(msg)
msg = '```diff' + '\n' + '- xdeath offline```'
queue.put(msg)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment