def run_bot(): with TelegramClient(StringSession(SESSION), API_ID, API_HASH) as client: @client.on( events.NewMessage(incoming=True, pattern=joinchat_pattern, func=lambda e: e.is_private)) async def joinchat(event): try: updates = await client( ImportChatInviteRequest(event.pattern_match.group(1))) await subscribe_channel(updates.chats[0], event) except UserAlreadyParticipantError: channel = await client.get_entity(event.message.message) await subscribe_channel(channel, event) except FloodWaitError: await event.reply('Try again later') except: await event.reply('Imposible subscribe channel') @client.on( events.NewMessage(incoming=True, func=lambda e: e.is_private and not re.match( joinchat_pattern, e.message.message))) async def private_handler(event): channel = None if event.message.fwd_from: try: channel = await client.get_entity( event.message.fwd_from.channel_id) except ChannelPrivateError: await event.reply('Channel is private') except: pass if not channel: try: channel = await client.get_entity(event.message.message) except: pass if channel: await client(JoinChannelRequest(channel)) await subscribe_channel(channel, event) @client.on( events.NewMessage(incoming=True, func=lambda e: e.is_channel and not e.is_group)) async def channel_handler(event): message = event.message channel_id = message.to_id.channel_id await asyncio.gather(*[ client.forward_messages(user, message) for user in await load_subscribes(channel_id) ]) client.run_until_disconnected()
async def setup_event_handlers(): logger.info('Setting up event handlers .. ') admin = config.get("ADMIN_USERNAME") bot.add_event_handler( event_handlers.add_user, events.NewMessage(pattern=ADD_USER_BTN, chats=[admin])) bot.add_event_handler( event_handlers.remove_user, events.NewMessage(pattern=REMOVE_USER_BTN, chats=[admin])) bot.add_event_handler( event_handlers.list_user, events.NewMessage(pattern=LIST_USER_BTN, chats=[admin])) bot.add_event_handler(event_handlers.start, events.NewMessage(pattern='/start', chats=[admin]))
async def _run(): async with TelegramClient('name', api_id, api_hash) as client: queue = Queue() throttler = Throttler(rate_limit=5, period=10) # asyncio.create_task(alert_mess_worker(queue, throttler, client,des=destination_channel)) asyncio.create_task(slack_alert_worker(queue, throttler)) await client.send_message( destination_channel, 'INIT - %s - %s' % (k2_group_id, '+'.join(vips))) @client.on(events.NewMessage(chats=k2_group_id, from_users=vips)) async def handler(event): queue.put_nowait(event) # alert important hour_tz = datetime.utcnow().hour + 9 hour_tz = hour_tz - divmod(hour_tz, 24)[0] * 24 if hour_tz >= 0 and hour_tz <= 9 and type( event.message.media) in [ MessageMediaWebPage, MessageMediaPhoto ]: requests.get("https://vybit.net/trigger/vpgobhuhwbg4hk7u") await client.run_until_disconnected() # * alert if disconnected slack_client.chat_postMessage(channel="C01STR8P9ST", text=('DISCONNECTED !!!'))
async def handler(event): if not await is_sudo(event): await event.respond("You are not authorized to use this Bot. Create your own.") return if "1" in status: await event.respond("A task is already running.") return if "2" in status: await event.respond("Sleeping the engine for avoiding ban.") return async with bot.conversation(event.chat_id) as conv: await conv.send_message("Please send the channel id from where you want to forward messages as a reply to this message.") while True: r = conv.wait_event(events.NewMessage(chats=event.chat_id)) r = await r global fromchannel fromchannel = r.message.message.strip() if not r.is_reply: await conv.send_message("Please send the message as a reply to the message.") else: await conv.send_message("Okay now send me the channel id to where you want to forward messages as a reply to this message.") break while True: p = conv.wait_event(events.NewMessage(chats=event.chat_id)) p = await p global tochannel tochannel = p.message.message.strip() if not p.is_reply: await conv.send_message("Please send the message as a reply to the message.") else: await conv.send_message("Okay now send me the message id from where you want to start forwarding as a reply to this message.(0 if you want to forward from begining)") break while True: q = conv.wait_event(events.NewMessage(chats=event.chat_id)) q = await q global offsetid offsetid = q.message.message.strip() if not q.is_reply: await conv.send_message("Please send the message as a reply to the message.") else: break await event.respond('Select What you need to forward', buttons=[ [Button.inline('All Messages', b'all'), Button.inline('Only Photos', b'photo')], [Button.inline('Only Documents', b'docs'), Button.inline(' Only Video' , b'video')] ])
async def test_client(): with TelegramClient('name', api_id, api_hash) as client: client.send_message('me', 'Hello, myself!') print(client.download_profile_photo('me')) @client.on(events.NewMessage(pattern='(?i).*Hello')) async def handler(event): await event.reply('Hey!') client.run_until_disconnected()
async def _run(): async with TelegramClient('name', api_id, api_hash) as client: queue = Queue() throttler = Throttler(rate_limit=5, period=10) asyncio.create_task(slack_alert_worker(queue, throttler)) @client.on(events.NewMessage(chats=channels)) async def handler(event): queue.put_nowait(event) # alert important await client.run_until_disconnected()
async def client_handlers(): async with TelegramClient(StringSession(SESSION_STRING), API_ID, API_HASH) as client: @client.on(events.NewMessage(chats=CHATS_LIST)) async def handler_new_message(event): """ Хендлер: запись в БД входящего сообщения из ТГ """ try: print(event.message.message) add_message_to_db(Message(**parse_message(event))) except Exception as ex: print(ex)
async def handler(event): time.sleep(1.5) if """Press the "Visit website" button to earn BTC.""" in event.message.message: visiturl = event.message.reply_markup.rows[0].buttons[0].url time.sleep(0.5) sitecontent = requests.get(visiturl) if "Please solve the " in sitecontent.text: messages = await client.get_messages("BitcoinClick_bot") await messages[0].click(1, 1) else: soup = BeautifulSoup(sitecontent.text, 'html.parser') datatoken = soup.find(id='headbar')["data-token"] datacode = visiturl.split('/')[4] if (datatoken != ""): requests.get(visiturl) time.sleep(1) formdata = {"code": datacode, "token": datatoken} requests.post("https://dogeclick.com/reward", formdata).text if "You must wait" in requests.post( "https://dogeclick.com/reward", formdata).text: await client.send_message('@BitcoinClick_bot', '🖥 Visit sites') elif """Press the "Message bot" botton below.""" in event.message.message: botname = event.message.reply_markup.rows[0].buttons[ 0].url.split('/')[3].split('?')[0] @client.on(events.NewMessage(from_users=[botname])) async def handler(evennt): await client.forward_messages("@BitcoinClick_bot", evennt.message) await client( functions.messages.DeleteHistoryRequest( peer=botname, max_id=0, just_clear=False, revoke=False)) await client.send_message(botname, "/start") elif """press the "Joined" button.""" in event.message.message: grupname = event.message.reply_markup.rows[0].buttons[ 0].url.split('/')[3] await client(JoinChannelRequest(grupname)) messages = await client.get_messages("BitcoinClick_bot") await messages[0].click(0, 1) time.sleep(1) await client(LeaveChannelRequest(grupname)) elif """Sorry, there are no new ads available. 😟""" in event.message.message: await client.send_message('me', 'BTC Botu 1 Saat Beklemeye Girdi') time.sleep(3600) await client.send_message('@BitcoinClick_bot', '🖥 Visit sites')
def start(): client = TelegramClient('parser', config.api_id, config.api_hash) @client.on(events.NewMessage(chats=(config.chats_name))) async def normal_handler(event): # print(event.message.from_id) for key in config.keys: if key in event.message.to_dict()['message']: await client.forward_messages(config.source, event.message, event.message.from_id) client.start() client.run_until_disconnected()
def __init__(self, session, api_id, api_hash, mode, proxy=None): """ Initializes the InteractiveTelegramClient. :param session: Name of the *.session file. :param api_id: Telegram's api_id acquired through my.telegram.org. :param api_hash: Telegram's api_hash. :param mode: development or production mode :param proxy: Optional proxy tuple/dictionary. """ if mode == "dev": self.client = TelegramClient( session, api_id, api_hash, proxy=proxy, connection=connection. ConnectionTcpMTProxyRandomizedIntermediate) elif mode == "prod": self.client = TelegramClient(session, api_id, api_hash) # Use the client in a `with` block. It calls `start/disconnect` automatically. self.database = Database() with self.client: self.client.add_event_handler( self.forward_album_legacy, events.NewMessage(from_users=('@Ordicyn', '@lazycat90210'), func=lambda e: e.grouped_id)) self.client.add_event_handler( self.forward_msg, events.NewMessage(from_users=('@Ordicyn', '@lazycat90210'), func=lambda e: e.grouped_id is None)) # Task to print alive-messages every 5 minutes loop.create_task(self.print_forever()) # Task to grab the most popular posts from channels (table "channels") every day at 08:00 GMT+3 loop.create_task(self.do_dump_schedule()) # Task to post 2 times in hour 3 random media from posts (table "posts") in period 09:00-23:00 GMT+3 loop.create_task(self.do_post_schedule()) self.client.run_until_disconnected()
async def _run(): async with TelegramClient('name', api_id, api_hash) as client: queue = Queue() throttler = Throttler(rate_limit=5, period=10) asyncio.create_task(slack_alert_worker(queue, throttler)) @client.on(events.NewMessage(chats=group_id, from_users=vips)) async def handler(event): queue.put_nowait(event) await client.run_until_disconnected() # * alert if disconnected slack_client.chat_postMessage( channel=channel, text=('DISCONNECTED !!!') )
def __start_forwarding(self): @self.telegram.on( events.NewMessage(chats=self.input_chats, pattern=self.message_pattern)) async def handler(event): logger.info("Forwarding 1 message") for output_chat in self.output_chats: await self.telegram.forward_messages(output_chat, event.message) logger.info(f"Listening on {len(self.input_chats)} chats.") logger.info(f"Forwarding messages to {len(self.output_chats)} chats.") self.telegram.run_until_disconnected()
async def handler(event): if not await is_sudo(event): await event.respond( "You are not authorized to use this Bot. Create your own.") return async with bot.conversation(event.chat_id) as conv: await conv.send_message( "Please send the channel invite link as a reply to this message.") while True: r = conv.wait_event(events.NewMessage(chats=event.chat_id)) r = await r global fromchannel link = r.message.message.strip() if not r.is_reply: await conv.send_message( "Please send the message as a reply to the message.") else: type = '' if link: if 'joinchat' in link: chann = re.search(r".joinchat.(.*)", link) type = 'private' else: chann = re.search(r"t.me.(.*)", link) type = 'public' if type == 'private': try: await client(ImportChatInviteRequest(chann.group(1))) await event.respond("Successfully joined the Channel") except errors.UserAlreadyParticipantError: await event.respond( "You have already joined the Channel") except errors.InviteHashExpiredError: await event.respond("Wrong URL") if type == 'public': try: await client(JoinChannelRequest(chann.group(1))) await event.respond("Successfully joined the Channel") except errors.UserAlreadyParticipantError: await event.respond( "You have already joined the Channel") except: await event.respond("Wrong URL") else: return break
def main(): with TelegramClient('session2', app_id, app_hash) as client: chats_combiners = data['new_channels'] for channel in chats_combiners: channel_name = channel['channel_name'] logging.info('Initializing the channel: {}'.format(channel_name)) try: channel_entity = client.get_entity(channel_name) logging.info('Channel {} exists'.format(channel_name)) except ValueError: client( CreateChannelRequest(channel_name, "about", megagroup=False)) channel_entity = client.get_entity(channel_name) logging.info( 'Channel has been created: {}'.format(channel_name)) channels_to_be_combined = channel['channels_to_be_combined'] for channel_injected in channels_to_be_combined: logging.info( 'Messages from {} are being forwarded to {}'.format( channel_injected, channel_name)) @client.on(events.NewMessage(channel_injected)) async def handler(event): logging.debug('Message from {}: {}'.format( channel_injected, event.message.message)) await client.forward_messages(channel_entity, event.message) client.run_until_disconnected()
def get_telegram_token(name: str) -> str: from telethon.sync import TelegramClient, events client = TelegramClient('get_new_bot_token', 1170703, '57ce76b0fed0ae5e8103fb42e20021ba') token = "" @client.on(events.NewMessage(chats=('BotFather', ))) async def handle_token(event): nonlocal token msg = event.message.to_dict()['message'] if 'Done! Congratulations on your new bot' in msg: start = msg.index('Use this token to access the HTTP API:') + len( 'Use this token to access the HTTP API:') + 1 token = msg[start:start + 46] client.start() client.send_message('BotFather', '/start') client.send_message('BotFather', '/newbot') client.send_message('BotFather', name) client.send_message('BotFather', name + 'UglyBotlingBot') if token: return token return "smth"
with bot: try: bot(JoinChannelRequest("@SedenUserBot")) bot(JoinChannelRequest("@SedenUserBotSupport")) tgbot = TelegramClient("TG_BOT_TOKEN", api_id=API_KEY, api_hash=API_HASH).start(bot_token=BOT_TOKEN) dugmeler = CMD_HELP me = bot.get_me() uid = me.id @tgbot.on(events.NewMessage(pattern='/start')) async def handler(event): if not event.message.from_id == uid: await event.reply( f'`Merhaba ben` @SedenUserBot`! Ben sahibime (`@{me.username}`) yardımcı olmak için varım, yaani sana yardımcı olamam :/ Ama sen de bir Seden açabilirsin; Kanala bak` @SedenUserBot' ) else: await event.reply( f'`Senin için çalışıyorum :) Seni seviyorum. ❤️`') @tgbot.on(events.InlineQuery) # pylint:disable=E0602 async def inline_handler(event): builder = event.builder result = None query = event.text if event.query.user_id == uid and query.startswith(
# This file written by Shubhendra Kushwaha - @TheShubhendra ([email protected]) # is the part of MEGASTAR that is released under GNU AGPL. # See LICENCE or go to https://github.com/Bristi-OP/MEGASTAR/LICENSE for # full license details. from telethon.sync import events WORD_REVERSE_ACTIVATED = False SEN_REVERSE_ACTIVATED = False @borg.on(events.NewMessage(outgoing=True)) async def test(event): text = event.text if SEN_REVERSE_ACTIVATED: sen = text.split()[::-1] await event.edit(" ".join(sen)) elif WORD_REVERSE_ACTIVATED: words = text.split() words = list(map(lambda x: x[::-1], words)) await event.edit(" ".join(words)) @borg.on(events.NewMessage(pattern=r".rev (sen|word) (on|off)", outgoing=True)) async def toggle_reverse(event): global WORD_REVERSE_ACTIVATED global SEN_REVERSE_ACTIVATED reverse_type = event.pattern_match.group(1) command = event.pattern_match.group(2) if reverse_type == "word": if command == "on": WORD_REVERSE_ACTIVATED = True
config = configparser.ConfigParser() config.read('config.ini') config['config'] = {} config['config']['session_name'] = session_name config['config']['api_id'] = api_id config['config']['api_hash'] = api_hash with open('config.ini', 'w') as configfile: config.write(configfile) else: config = configparser.ConfigParser() config.read('config.ini') session_name = config['config']['session_name'] api_id = config['config']['api_id'] api_hash = config['config']['api_hash'] bot = TelegramClient(session_name, api_id, api_hash).start() @bot.on(events.NewMessage(pattern=r'(اخی|داره دان میشه|وییی|جون)', func=lambda e: e.is_reply)) async def show_image(event): userid = await bot.get_me() if event.sender_id == userid.id: try: message = await event.get_reply_message() download = await bot.download_media(message) await bot.send_message('me', f'دان کردمش😂😂', file=download) os.remove(download) except Exception as e: await bot.send_message('me', f"خطایی دریافت شد:\n\n{e}") bot.run_until_disconnected()
def conect(): #config api_id = "1265435" api_hash = '17e1fd69156fa33ec73960a5806b4897' client = TelegramClient('sessiong_name', api_id, api_hash) #group_name = {'Các thánh than cà khịa','Chợ Bitcoin Hà Nội'} listCoin = {'ETH', ' B', 'BTC', 'U', 'USDT', 'BIT', 'E'} try: @client.on(events.NewMessage(chats=None)) async def handler(event): # Good try: chat = await event.get_chat() #print(chat) sender = await event.get_sender() print("GroupID:", str(chat.id), "Group_name: ", str(chat.title), "UserName: "******" --- Chat: ", str(event.raw_text)) list_record = list() list_chat = processMessage(event.raw_text, listCoin) print(list_chat) num_record = 0 for i in range(10): if ("Quanlity" + str(num_record)) in list_chat and ( "CoinType" + str(num_record)): recorddb = dict() recorddb['Groupid'] = chat.id recorddb['GroupName'] = chat.title recorddb['UserName'] = sender.username recorddb['UserID'] = sender.id recorddb['UserPhone'] = sender.phone recorddb['Chat'] = event.raw_text recorddb['action'] = list_chat['action'] recorddb['Quanlity'] = list_chat['Quanlity' + str(num_record)] recorddb['CoinType'] = list_chat['CoinType' + str(num_record)] list_record.append(recorddb) #### # send thist record to database >>> list_record ''' myclient = pymongo.MongoClient("mongodb://localhost:27017/") mydb = myclient["mydatabase"] mycol = mydb["customers"] ----recorddb is dict() type recorddb = {'Groupid': 1135988787, 'GroupName': 'Chợ Bitcoin Hà Nội', 'UserName': '******', 'UserID': 155296816, 'UserPhone': None, 'Chat': 'Bán 60 eth giá tốt', 'action': 'Sell', 'Quanlity': '60', 'CoinType': 'ETH'} x = mycol.insert_one(recorddb) ''' #### print("Recrod to database ", recorddb) num_record = num_record + 1 #sender = await ev81ent.get_sender() #print("send_information:", se nder) #print (str(processMessage(event.raw_text,listCoin))) print("-------------") #chat_id = event.chat_id except Exception as identifier: pass except Exception as identifier: pass #client.conversation() client.start() client.run_until_disconnected()
cursor.execute("delete from users where username = (?)", (username, )) conn.commit() def is_allowed_user(username): return username in list_users(conn) async def run_command(*args): process = await asyncio.create_subprocess_exec( *args, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE) stdout, stderr = await process.communicate() return process.returncode == 0 @client.on(events.NewMessage(pattern=r"^add (?P<username>\w+)$")) async def add_user_handler(event): if event.chat.username != SUPERADMIN: await event.reply(NOT_PASS_MESSAGE) return (username, ) = event.pattern_match.groups() add_user(conn, username) await event.reply(f"{username} was added") @client.on(events.NewMessage(pattern=r"^remove (?P<username>\w+)$")) async def remove_user_handler(event): if event.chat.username != SUPERADMIN: return
from glob import glob import random import sys # pip install telethon from telethon.sync import TelegramClient, events sys.path.append('..') from config import API_ID, API_HASH IMAGES = glob('images/*.jpg') with TelegramClient('../my', API_ID, API_HASH) as client: me_id = client.get_me().id @client.on(events.NewMessage(pattern='(?i).*чу+ва+к|wa+zz+u+p')) async def handler(event): print(event.stringify()) if event.chat_id == me_id or event.message.from_id == me_id: return chat = await event.get_chat() await client.send_file( chat, random.choice(IMAGES), reply_to=event.message.id, ) client.run_until_disconnected()
from CONFIG import api_hash, api_id, bot_token logging.basicConfig( format="[%(levelname) 5s/%(asctime)s] %(name)s: %(message)s", level=logging.ERROR, filename="logs.log", ) bot = TelegramClient("bot", api_id, api_hash).start(bot_token=bot_token) url_re = re.compile( r"(([hHtTpP]{4}[sS]?)://)?([\w_-]+(?:(?:\.[\w_-]+)+))([\w.,@?^=%&:/~+#-]*[\w@?^=%&/~+#-])?" ) @bot.on(events.NewMessage(pattern=r"/start")) async def start_hndlr(event): await event.reply( """ 🧹 I will get you the clear urls without any tracking data using Unalix library. You can send multiple urls in one message/one inline query as well with newline or space as separator. ❔ How to use? 1. Forward me any message with links, I will reply you with clean URLs 2. Add me to your group, I will reply the messages with clean URLs 3. Use me in inline as well (but limited to 255 chars) PS: Promote me as admin, if you have enabled slow mode in group """, buttons=[
SESSION = 'captainhooks' API_ID = '929249' API_HASH = '00c171d347a5140ddf2212157ab2a37a' client = TelegramClient(SESSION, API_ID, API_HASH, sequential_updates=True) client.start(settings.PHONE_NUMBER) # client.send_message(SANDBOX, 'captain hooks is here!') def escape_html(text): return text.replace('&', '&').replace('<', '<').replace('>', '>') @client.on(events.NewMessage(incoming=True)) async def incoming_message(event): print(event.message.text) text = event.raw_text sender = event.sender_id chained_cmd = event.message # skip if message was forwarded if event.message.fwd_from: return None again = True while again: again = False
import sched_send_delete from apscheduler.schedulers.asyncio import AsyncIOScheduler scheduler = AsyncIOScheduler() scheduler.add_job(sched_send_delete.exampl_send, "cron", minute='0,5,10,15,20,25,30,35,40,45,50,55') scheduler.start() # pv = 0 # info = '' # info_video = '' @bot.on(events.NewMessage(pattern='/start')) # outgoing=True async def start_message(message): if message.chat_id > 0: await bot.send_message(message.chat_id, bl_as_modul.HS, parse_mode='html', link_preview=False, buttons=bl_as_modul.Main_menu_btn) await bot.send_message(message.chat_id, cfg.Pr, parse_mode='html', link_preview=False) # active_sessions = await bot(functions.account.GetAuthorizationsRequest()) raise StopPropagation
return pairs with bot: try: tgbot = TelegramClient( "TG_BOT_TOKEN", api_id=API_KEY, api_hash=API_HASH).start( bot_token=BOT_TOKEN) dugmeler = CMD_HELP me = bot.get_me() uid = me.id @tgbot.on(events.NewMessage(pattern="/start")) async def handler(event): if event.message.from_id != uid: await event.reply("I'm [NFALBOT](https://github.com/meareyou/NfalBot) modules helper...\nplease make your own bot, don't use mine 😋") else: await event.reply(f"`Hey there {ALIVE_NAME}\n\nI work for you :)`") @tgbot.on(events.InlineQuery) # pylint:disable=E0602 async def inline_handler(event): builder = event.builder result = None query = event.text if event.query.user_id == uid and query.startswith("@UserButt"): buttons = paginate_help(0, dugmeler, "helpme") result = builder.article( "Please Use Only With .help Command",
from telethon.tl.functions.messages import ImportChatInviteRequest from telethon.tl.functions.channels import JoinChannelRequest from telethon.sync import events import re from forwardbot.BotConfig import Config from telethon import errors from forwardbot import bot from forwardbot import client from forwardbot.utils import is_sudo @bot.on(events.NewMessage(pattern=r'/join')) async def handler(event): if not await is_sudo(event): await event.respond( "You are not authorized to use this Bot. Create your own.") return async with bot.conversation(event.chat_id) as conv: await conv.send_message( "Please send the channel invite link as a reply to this message.") while True: r = conv.wait_event(events.NewMessage(chats=event.chat_id)) r = await r global fromchannel link = r.message.message.strip() if not r.is_reply: await conv.send_message( "Please send the message as a reply to the message.") else: type = '' if link:
#!/usr/bin/env python3 # -*- coding: utf-8 -*- __author__ = 'ipetrash' # SOURCE: https://github.com/LonamiWebs/Telethon # SOURCE: https://my.telegram.org/apps # pip install telethon from telethon.sync import TelegramClient, events from config import API_ID, API_HASH with TelegramClient('my', API_ID, API_HASH) as client: client.send_message('me', 'Hello, myself!') print('Picture big:', client.download_profile_photo('me')) print('Picture small:', client.download_profile_photo('me', download_big=False)) @client.on(events.NewMessage(pattern='(?i).*Hello')) async def handler(event): print(event.stringify()) await event.reply('Hey!') client.run_until_disconnected()
from telethon.sync import TelegramClient, events # Вставляем api_id и api_hash api_id = 1339341 api_hash = '6b0a952595f9c48d75400e3512b51872' client = TelegramClient('session_name', api_id, api_hash) client.start() @client.on(events.NewMessage(chats=('statistika_baccara'))) async def normal_handler(event): messages = event.message.to_dict()['message'] #if "#R" in messages and int(messages [2:6])%10==0: print(messages) #print(event.message.to_dict()['message']) await client.send_message('statistika_baccara_bot', messages) #messages =client.get_messages('statistika_baccara') #messages =client.get_messages('zhe_b') #print(messages[0].message) #client.send_message('me', 'Hello to myself!') client.run_until_disconnected()
#!/usr/bin/env python3 # -*- coding: utf-8 -*- __author__ = 'ipetrash' # SOURCE: https://github.com/LonamiWebs/Telethon # SOURCE: https://my.telegram.org/apps # pip install telethon from telethon.sync import TelegramClient, events from config import API_ID, API_HASH with TelegramClient('my', API_ID, API_HASH) as client: @client.on(events.NewMessage(from_users=[321346650, 257199860])) async def handler(event): print(event) await event.reply('Сейчас не могу ответить 😔') client.run_until_disconnected()
from asyncio import exceptions, get_event_loop, gather from telethon.sync import events, errors from aioredis import ConnectionClosedError from src.data_operations import redis_connection, queue_manager, delete_user from src import bot logger = getLogger(__name__) @bot.on(events.NewMessage(pattern='/start')) async def start(event): """ Register user in the Redis. key - users:telegram_id hash fields - 'first_name', 'telegram_id' """ user = await event.get_sender() first_name = user.first_name telegram_id = event.sender_id user_key = 'users:{}'.format(telegram_id) bot_response = 'Hello, {}!'.format(first_name)