Skip to content

Instantly share code, notes, and snippets.

@udf
Created May 1, 2020 19:35
Show Gist options
  • Save udf/4e70df8ffa06bb4a36a5a20f2d6d5071 to your computer and use it in GitHub Desktop.
Save udf/4e70df8ffa06bb4a36a5a20f2d6d5071 to your computer and use it in GitHub Desktop.
Automates botfather and dumps all your bot tokens, does not get usernames, only tokens.
import re
import logging
import asyncio
import telethon
import itertools
from telethon import TelegramClient, events
logging.basicConfig(level=logging.INFO)
def find_button_with_text(buttons, text):
for button in itertools.chain.from_iterable(buttons):
if button.text == text:
return button
if callable(text) and text(button.text):
return button
async def get_all_tokens(conv, reply):
async def click_button(button):
response = conv.get_edit()
await button.click()
return await response
seen = set()
tokens = []
while 1:
# find button to click
target = None
next_button = None
for button in itertools.chain.from_iterable(reply.buttons):
if button.text.startswith('@') and button.text not in seen:
seen.add(button.text)
target = button
break
if button.text == '»':
next_button = button
# go to next page if we've checked all
if not target and next_button:
reply = await click_button(next_button)
continue
# return if nothing to do
if not target and not next_button:
return tokens
# go to bot page and click token button
reply = await click_button(target)
b = find_button_with_text(reply.buttons, 'API Token')
reply = await click_button(b)
# get token
token = re.search('\d+:[A-Za-z0-9-_]+', reply.raw_text).group(0)
tokens.append(token)
# go back to list
b = find_button_with_text(reply.buttons, lambda s: 'Back' in s)
reply = await click_button(b)
b = find_button_with_text(reply.buttons, lambda s: 'Back' in s)
reply = await click_button(b)
async def main():
client = TelegramClient('durov', 6, 'eb06d4abfb49dc3eeb1aeb98ae0f581e')
client.flood_sleep_threshold = 999999
await client.start()
# Note: a better way to do this would be to:
# - observe bot buttons to get all the ids
# - the for each button that we've seen:
# - click it, click the token button
# However this isn't possible since we can only click buttons that exist on
# the message, so no fancy jumping around.
#
# Thanks Durov
async with client.conversation('@BotFather') as conv:
await conv.send_message('/mybots')
reply = await conv.get_response()
tokens = await get_all_tokens(conv, reply)
for token in tokens:
print(token)
asyncio.run(main())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment