Update examples

This commit is contained in:
Lonami Exo 2018-05-24 10:58:42 +02:00
parent 03f0044ef8
commit e5ff534e2e
3 changed files with 40 additions and 36 deletions

View File

@ -3,7 +3,8 @@ from getpass import getpass
from telethon.utils import get_display_name from telethon.utils import get_display_name
from telethon import ConnectionMode, TelegramClient from telethon import TelegramClient, events
from telethon.network import ConnectionTcpAbridged
from telethon.errors import SessionPasswordNeededError from telethon.errors import SessionPasswordNeededError
from telethon.tl.types import ( from telethon.tl.types import (
PeerChat, UpdateShortChatMessage, UpdateShortMessage PeerChat, UpdateShortChatMessage, UpdateShortMessage
@ -70,11 +71,11 @@ class InteractiveTelegramClient(TelegramClient):
# These parameters should be passed always, session name and API # These parameters should be passed always, session name and API
session_user_id, api_id, api_hash, session_user_id, api_id, api_hash,
# You can optionally change the connection mode by using this enum. # You can optionally change the connection mode by passing a
# This changes how much data will be sent over the network with # type or an instance of it. This changes how the sent packets
# every request, and how it will be formatted. Default is # look (low-level concept you normally shouldn't worry about).
# ConnectionMode.TCP_FULL, and smallest is TCP_TCP_ABRIDGED. # Default is ConnectionTcpFull, smallest is ConnectionTcpAbridged.
connection_mode=ConnectionMode.TCP_ABRIDGED, connection=ConnectionTcpAbridged,
# If you're using a proxy, set it here. # If you're using a proxy, set it here.
proxy=proxy, proxy=proxy,
@ -126,10 +127,11 @@ class InteractiveTelegramClient(TelegramClient):
def run(self): def run(self):
"""Main loop of the TelegramClient, will wait for user action""" """Main loop of the TelegramClient, will wait for user action"""
# Once everything is ready, we can add an update handler. Every # Once everything is ready, we can add an event handler.
# update object will be passed to the self.update_handler method, #
# where we can process it as we need. # Events are an abstraction over Telegram's "Updates" and
self.add_update_handler(self.update_handler) # are much easier to use.
self.add_event_handler(self.message_handler, events.NewMessage)
# Enter a while loop to chat as long as the user wants # Enter a while loop to chat as long as the user wants
while True: while True:
@ -334,31 +336,29 @@ class InteractiveTelegramClient(TelegramClient):
bytes_to_string(total_bytes), downloaded_bytes / total_bytes) bytes_to_string(total_bytes), downloaded_bytes / total_bytes)
) )
def update_handler(self, update): def message_handler(self, event):
"""Callback method for received Updates""" """Callback method for received events.NewMessage"""
# We have full control over what we want to do with the updates. # Note that accessing ``.sender`` and ``.chat`` may be slow since
# In our case we only want to react to chat messages, so we use # these are not cached and must be queried always! However it lets
# isinstance() to behave accordingly on these cases. # us access the chat title and user name.
if isinstance(update, UpdateShortMessage): if event.is_group:
who = self.get_entity(update.user_id) if event.out:
if update.out: sprint('>> sent "{}" to chat {}'.format(
event.text, get_display_name(event.chat)
))
else:
sprint('<< {} @ {} sent "{}"'.format(
get_display_name(event.sender),
get_display_name(event.chat),
event.text
))
else:
if event.out:
sprint('>> "{}" to user {}'.format( sprint('>> "{}" to user {}'.format(
update.message, get_display_name(who) event.text, get_display_name(event.chat)
)) ))
else: else:
sprint('<< {} sent "{}"'.format( sprint('<< {} sent "{}"'.format(
get_display_name(who), update.message get_display_name(event.chat), event.text
))
elif isinstance(update, UpdateShortChatMessage):
which = self.get_entity(PeerChat(update.chat_id))
if update.out:
sprint('>> sent "{}" to chat {}'.format(
update.message, get_display_name(which)
))
else:
who = self.get_entity(update.from_id)
sprint('<< {} @ {} sent "{}"'.format(
get_display_name(which), get_display_name(who), update.message
)) ))

View File

@ -1,5 +1,9 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
# A simple script to print all updates received # A simple script to print all updates received
#
# 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.
from os import environ from os import environ
@ -23,7 +27,7 @@ def main():
else: else:
client.start() client.start()
client.add_update_handler(update_handler) client.add_event_handler(update_handler)
print('(Press Ctrl+C to stop this)') print('(Press Ctrl+C to stop this)')
client.idle() client.idle()

View File

@ -2,9 +2,9 @@
""" """
A example 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, NOTE: To run this script you MUST have 'TG_API_ID' and 'TG_API_HASH' in
hash, phone and such to be used. You may want to add these to your .bashrc your environment variables. This is a good way to use these private
file, including TG_API_ID, TG_API_HASH, TG_PHONE and optionally TG_SESSION. values. See https://superuser.com/q/284342.
This script assumes that you have certain files on the working directory, 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. such as "xfiles.m4a" or "anytime.png" for some of the automated replies.