From f6cb9667d53c7e1eb10823d1be88317c0a1e7735 Mon Sep 17 00:00:00 2001 From: Lonami Exo Date: Fri, 27 Oct 2017 18:17:04 +0200 Subject: [PATCH 1/2] Update the code the way I like it --- telethon_examples/replier.py | 74 ++++++++++++++++++++---------------- 1 file changed, 42 insertions(+), 32 deletions(-) diff --git a/telethon_examples/replier.py b/telethon_examples/replier.py index 954b9878..4589a51c 100755 --- a/telethon_examples/replier.py +++ b/telethon_examples/replier.py @@ -1,28 +1,37 @@ #!/usr/bin/env python3 -# A script to automatically send messages based on certain triggers +""" +A example script to automatically send messages based on certain triggers. + +The script makes uses of environment variables to determine the API ID, +hash, phone and such to be used. You may want to add these to your .bashrc +file, including TG_API_ID, TG_API_HASH, TG_PHONE and optionally TG_SESSION. + +This script assumes that you have certain files on the working directory, +such as "xfiles.m4a" or "anytime.png" for some of the automated replies. +""" from getpass import getpass from collections import defaultdict from datetime import datetime, timedelta from os import environ -# environ is used to get API information from environment variables -# You could also use a config file, pass them as arguments, -# or even hardcode them (not recommended) -from nltk.tokenize import word_tokenize -# NLTK is used to match specific triggers in messages + +import re + from telethon import TelegramClient from telethon.errors import SessionPasswordNeededError from telethon.tl.types import UpdateNewChannelMessage, UpdateShortMessage, MessageService from telethon.tl.functions.messages import EditMessageRequest -# Uncomment this for debugging -# import logging -# logging.basicConfig(level=logging.DEBUG) -# logging.debug('dbg') -# logging.info('info') +"""Uncomment this for debugging +import logging +logging.basicConfig(level=logging.DEBUG) +logging.debug('dbg') +logging.info('info') +""" REACTS = {'emacs': 'Needs more vim', 'chrome': 'Needs more Firefox'} + def setup(): try: global recent_reacts @@ -32,11 +41,10 @@ def setup(): global client session_name = environ.get('TG_SESSION', 'session') user_phone = environ['TG_PHONE'] - client = TelegramClient(session_name, - int(environ['TG_API_ID']), - environ['TG_API_HASH'], - proxy=None, - update_workers=4) + client = TelegramClient( + session_name, int(environ['TG_API_ID']), environ['TG_API_HASH'], + proxy=None, update_workers=4 + ) print('INFO: Connecting to Telegram Servers...', end='', flush=True) client.connect() @@ -54,13 +62,14 @@ def setup(): password = getpass('Two step verification enabled. ' 'Please enter your password: ') code_ok = client.sign_in(password=password) - print('INFO: Client initialized succesfully!') + print('INFO: Client initialized successfully!') client.add_update_handler(update_handler) input('Press Enter to stop this!\n') finally: client.disconnect() + def update_handler(update): global recent_reacts try: @@ -74,7 +83,7 @@ def update_handler(update): # React to messages in supergroups and PMs if isinstance(update, UpdateNewChannelMessage): - words = word_tokenize(msg.message) + words = re.split('\W+', msg.message) for trigger, response in REACTS.items(): if len(recent_reacts[msg.to_id.channel_id]) > 3: break @@ -82,16 +91,16 @@ def update_handler(update): if trigger in words: recent_reacts[msg.to_id.channel_id] = [ a for a in recent_reacts[msg.to_id.channel_id] if - datetime.now() - a < timedelta(minutes=10)] + datetime.now() - a < timedelta(minutes=10) + ] # Remove recents older than 10 minutes client.send_message(msg.to_id, response, reply_to=msg.id) # Send a reaction recent_reacts[msg.to_id.channel_id].append(datetime.now()) # Add this reaction to the recents list - if isinstance(update, UpdateShortMessage): - words = word_tokenize(msg) + words = re.split('\W+', msg) for trigger, response in REACTS.items(): if len(recent_reacts[update.user_id]) > 3: break @@ -99,12 +108,13 @@ def update_handler(update): if trigger in words: recent_reacts[update.user_id] = [ a for a in recent_reacts[update.user_id] if - datetime.now() - a < timedelta(minutes=10)] - # Remove recents older than 10 minutes + datetime.now() - a < timedelta(minutes=10) + ] + # Remove recent replies older than 10 minutes client.send_message(update.user_id, response, reply_to=update.id) # Send a reaction recent_reacts[update.user_id].append(datetime.now()) - # Add this reaction to the recents list + # Add this reaction to the list of recent reactions # Automatically send relevant media when we say certain things # When invoking requests, get_input_entity needs to be called manually @@ -114,9 +124,10 @@ def update_handler(update): if msg.message.lower() == 'anytime': client.send_file(msg.to_id, 'anytime.png', reply_to=msg.id) if '.shrug' in msg.message: - client( - EditMessageRequest(client.get_input_entity(msg.to_id), msg.id, - message=msg.message.replace('.shrug', r'¯\_(ツ)_/¯'))) + client(EditMessageRequest( + client.get_input_entity(msg.to_id), msg.id, + message=msg.message.replace('.shrug', r'¯\_(ツ)_/¯') + )) if isinstance(update, UpdateShortMessage) and update.out: if msg.lower() == 'x files theme': @@ -124,11 +135,10 @@ def update_handler(update): if msg.lower() == 'anytime': client.send_file(update.user_id, 'anytime.png', reply_to=update.id) if '.shrug' in msg: - client( - EditMessageRequest(client.get_input_entity(update.user_id), update.id, - message=msg.replace('.shrug', r'¯\_(ツ)_/¯'))) - - + client(EditMessageRequest( + client.get_input_entity(update.user_id), update.id, + message=msg.replace('.shrug', r'¯\_(ツ)_/¯') + )) if __name__ == '__main__': From 651f70262bf77070a3660597170cdd9018ce7a1f Mon Sep 17 00:00:00 2001 From: Lonami Exo Date: Sat, 28 Oct 2017 11:05:58 +0200 Subject: [PATCH 2/2] More cleanup --- telethon_examples/anytime.png | Bin 0 -> 2291 bytes telethon_examples/replier.py | 92 ++++++++++++++++------------------ 2 files changed, 42 insertions(+), 50 deletions(-) create mode 100644 telethon_examples/anytime.png diff --git a/telethon_examples/anytime.png b/telethon_examples/anytime.png new file mode 100644 index 0000000000000000000000000000000000000000..c8663cfa21f253019a139d9c41f279b3134f0ecb GIT binary patch literal 2291 zcmbu8c{J4R9>9OIG4>{dFtW_3i7^?*R(1`dE;9_Fx@BvSZ4hR-F+~ioQYgjP#+Id~ z*D@&*VJtV*-|?;m&hKIePRbI$Yme$V%Fp6A(qz5Nc@+2}B}Mb-#(3v7RYjpQyLf1SBRVCMhAgM@njso;pfh@4t@iRsaD90)UGU zkOlxofFKCa_A@{g06;L|v^xX;GeBSn6ec1H7ZaBd0`zN9rYJ7QxZhyr*)MfiD<+Z#qj%TwY<1qLSvm{n!IqL<2)3W0ONR zM@Y7I_D3CDT&ZsECp>t5MO~e{XVAJFPMVui12~S6@EjyDJr0_#P&|uEovbjtTAR)Ud^D;P>(^ zkKY(<=*F+B%jm%#vm+$m_F(6idMPJM%bWxV&tnseue8y+k;+q#bBr>JY~zd2Y9eTK zTPTDPSsYWygk8zin^panHx2`LQ?7TV*zCrOWaW8%{oC@5NJT z)~r*SQ+}MoNp(i*99rx7y)26-tV4zu#RWek+XSbkRIzzJ{l_=MH}oH^RY}y&5^T{P zH)v_yQ%KE{PQ&ZA_FXC=Z17T##&=R>|k}?EVb2~-_KypQ6E1}>Ci9h44dDLIlj=3bCv44 z(cSOj$Yi1#4Bf)CQ))(X(-I`?U%!c2XiMB$WPZ5JxfC2oE@o?`?0hj|0V&r%`Lz?| zv_sDmf6Dk!nBYx#9dosd5yy}m>J=ZK@cc8X<&3PhuBG77EmVctqzbR!lNm%afEySu zIzF10%C``F04-YNOBsHCM_-KqcKsujy&xQ|5 z=j1^;Nb0uV1Y zmMABK_JuaE@V*MVIQ80)xL1}K_qoK(mB~FSfu-5gqcFkB#aXbST8B6jf`ZU^~G;K=ft^ru#zEKRQ&n@n+s zO>OWcw1J+DVmqq4YS2E}^oUQB<7VNU;k3J@e<`mZUYeh&)T=uB$lOw|Bxh#TC$t_g zKPZ*M!Nl7RO+E6mgJWPUxIfWX3L#(AX1cJ+si^X<9bmA|%0znMn))KCk->_?`_j!f$w zWmxhHLS|+cvY}rq#GE-co@^2QYDi@pC^Jd>8 xfxJ89PP4%sY^`P_EY0doaJx|t{qfp&*Q!{0T78H=^?6vWoq;tQFK@9u`Zo{N?wSAq literal 0 HcmV?d00001 diff --git a/telethon_examples/replier.py b/telethon_examples/replier.py index 4589a51c..66026363 100755 --- a/telethon_examples/replier.py +++ b/telethon_examples/replier.py @@ -31,43 +31,8 @@ logging.info('info') REACTS = {'emacs': 'Needs more vim', 'chrome': 'Needs more Firefox'} - -def setup(): - try: - global recent_reacts - # A list of dates of reactions we've sent, so we can keep track of floods - recent_reacts = defaultdict(list) - - global client - session_name = environ.get('TG_SESSION', 'session') - user_phone = environ['TG_PHONE'] - client = TelegramClient( - session_name, int(environ['TG_API_ID']), environ['TG_API_HASH'], - proxy=None, update_workers=4 - ) - - print('INFO: Connecting to Telegram Servers...', end='', flush=True) - client.connect() - print('Done!') - - if not client.is_user_authorized(): - print('INFO: Unauthorized user') - client.send_code_request(user_phone) - code_ok = False - while not code_ok: - code = input('Enter the auth code: ') - try: - code_ok = client.sign_in(user_phone, code) - except SessionPasswordNeededError: - password = getpass('Two step verification enabled. ' - 'Please enter your password: ') - code_ok = client.sign_in(password=password) - print('INFO: Client initialized successfully!') - - client.add_update_handler(update_handler) - input('Press Enter to stop this!\n') - finally: - client.disconnect() +# A list of dates of reactions we've sent, so we can keep track of floods +recent_reacts = defaultdict(list) def update_handler(update): @@ -86,35 +51,32 @@ def update_handler(update): words = re.split('\W+', msg.message) for trigger, response in REACTS.items(): if len(recent_reacts[msg.to_id.channel_id]) > 3: + # Silently ignore triggers if we've recently sent 3 reactions break - # Silently ignore triggers if we've recently sent three reactions + if trigger in words: + # Remove recent replies older than 10 minutes recent_reacts[msg.to_id.channel_id] = [ a for a in recent_reacts[msg.to_id.channel_id] if datetime.now() - a < timedelta(minutes=10) ] - # Remove recents older than 10 minutes - client.send_message(msg.to_id, response, reply_to=msg.id) # Send a reaction + client.send_message(msg.to_id, response, reply_to=msg.id) + # Add this reaction to the list of recent actions recent_reacts[msg.to_id.channel_id].append(datetime.now()) - # Add this reaction to the recents list if isinstance(update, UpdateShortMessage): words = re.split('\W+', msg) for trigger, response in REACTS.items(): if len(recent_reacts[update.user_id]) > 3: + # Silently ignore triggers if we've recently sent 3 reactions break - # Silently ignore triggers if we've recently sent three reactions + if trigger in words: - recent_reacts[update.user_id] = [ - a for a in recent_reacts[update.user_id] if - datetime.now() - a < timedelta(minutes=10) - ] - # Remove recent replies older than 10 minutes - client.send_message(update.user_id, response, reply_to=update.id) # Send a reaction - recent_reacts[update.user_id].append(datetime.now()) + client.send_message(update.user_id, response, reply_to=update.id) # Add this reaction to the list of recent reactions + recent_reacts[update.user_id].append(datetime.now()) # Automatically send relevant media when we say certain things # When invoking requests, get_input_entity needs to be called manually @@ -142,4 +104,34 @@ def update_handler(update): if __name__ == '__main__': - setup() + session_name = environ.get('TG_SESSION', 'session') + user_phone = environ['TG_PHONE'] + client = TelegramClient( + session_name, int(environ['TG_API_ID']), environ['TG_API_HASH'], + proxy=None, update_workers=4 + ) + try: + print('INFO: Connecting to Telegram Servers...', end='', flush=True) + client.connect() + print('Done!') + + if not client.is_user_authorized(): + print('INFO: Unauthorized user') + client.send_code_request(user_phone) + code_ok = False + while not code_ok: + code = input('Enter the auth code: ') + try: + code_ok = client.sign_in(user_phone, code) + except SessionPasswordNeededError: + password = getpass('Two step verification enabled. ' + 'Please enter your password: ') + code_ok = client.sign_in(password=password) + print('INFO: Client initialized successfully!') + + client.add_update_handler(update_handler) + input('Press Enter to stop this!\n') + except KeyboardInterrupt: + pass + finally: + client.disconnect()