Skip to content

Instantly share code, notes, and snippets.

@Aero-Blue
Created March 24, 2020 23:51
Show Gist options
  • Save Aero-Blue/effad8681ddd5642806b0fb8e24b80a3 to your computer and use it in GitHub Desktop.
Save Aero-Blue/effad8681ddd5642806b0fb8e24b80a3 to your computer and use it in GitHub Desktop.
Telegram bot made with Telethon that sends a message to all members of a specified group
from telethon.sync import TelegramClient
import asyncio
from os import path
# Logging configuration
def login(phone, api_id, api_hash):
global client
client = TelegramClient(phone, int(api_id), api_hash)
client.connect()
if not client.is_user_authorized(): # If further authentication is needed via text
client.send_code_request(phone)
print('Further authentication required in order to log in, a code has been sent to the phone number.')
client.sign_in(phone, input('Enter the code: '))
print(f"Logged in as {client.get_me().username}!")
async def get_users(group):
user_list = await client.get_participants(group)
users = [user.username for user in user_list if user.username is not None]
with open(input('Output file: '), 'w+') as f:
for user in users:
f.write(user+"\n")
print(f"{len(user_list)} users exported to {f.name}!")
async def send_messages(message, users):
for user in users:
await client.send_message(user, message)
print(f"Message sent to {user}.")
def save_credentials(*args):
print('Saving credentials...')
with open('creds.txt', 'w+') as f:
for arg in args:
f.write(f'{arg}\n')
def read_credentials():
print('Reading credentials...')
with open('creds.txt', 'r') as f:
return [line for line in f.read().split('\n') if line is not '']
def load_users():
with open('users.txt', 'r') as f:
return f.read().split('\n')
def main():
# Check if credentials are saved, otherwise get them from the user
if path.exists('creds.txt'):
credentials = read_credentials()
login(*credentials)
else:
# Needed for login authentication
print('Find these at https://my.telegram.org/ under API Development tools.')
save_credentials(
input('Phone # (EX: +11234560000): '),
input('api_id (EX: 101340): '),
input('api_hash (EX: ca123req3410fdls343207cc743): ')
)
credentials = read_credentials()
login(*credentials)
# Async routines
loop = asyncio.get_event_loop()
loop.run_until_complete(get_users(input('Group name: ')))
loop.run_until_complete(send_messages(input('Message: '), load_users()))
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment