Feature 'with client:' syntax in the examples

This commit is contained in:
Lonami Exo 2018-06-27 10:03:26 +02:00
parent e604960a1d
commit b834b6c16c
2 changed files with 20 additions and 27 deletions

View File

@ -4,37 +4,33 @@
# NOTE: To run this script you MUST have 'TG_API_ID' and 'TG_API_HASH' in
# your environment variables. This is a good way to use these private
# values. See https://superuser.com/q/284342.
import asyncio
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 telethon import TelegramClient
async def main():
session_name = environ.get('TG_SESSION', 'session')
client = TelegramClient(session_name,
int(environ['TG_API_ID']),
client = TelegramClient(
environ.get('TG_SESSION', 'session'),
environ['TG_API_ID'],
environ['TG_API_HASH'],
proxy=None)
if 'TG_PHONE' in environ:
await client.start(phone=environ['TG_PHONE'])
else:
await client.start()
client.add_event_handler(update_handler)
print('(Press Ctrl+C to stop this)')
await client.disconnected
proxy=None
)
async def update_handler(update):
print(update)
if __name__ == '__main__':
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
client.add_event_handler(update_handler)
'''You could also have used the @client.on(...) syntax:
from telethon import events
@client.on(events.Raw)
async def update_handler(update):
print(update)
'''
with client.start():
print('(Press Ctrl+C to stop this)')
client.run_until_disconnected()

View File

@ -10,7 +10,6 @@ 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.
"""
import re
import asyncio
from collections import defaultdict
from datetime import datetime, timedelta
from os import environ
@ -77,8 +76,6 @@ async def my_handler(event: events.NewMessage.Event):
await event.edit(event.text.replace('.shrug', r'¯\_(ツ)_/¯'))
if __name__ == '__main__':
loop = asyncio.get_event_loop()
loop.run_until_complete(client.start(phone=environ.get('TG_PHONE')))
with client.start():
print('(Press Ctrl+C to stop this)')
client.run_until_disconnected()