Giter Site home page Giter Site logo

lonamiwebs / telethon Goto Github PK

View Code? Open in Web Editor NEW
9.4K 149.0 1.4K 9.12 MB

Pure Python 3 MTProto API Telegram client library, for bots too!

Home Page: https://docs.telethon.dev

License: MIT License

Python 97.56% Makefile 0.05% Batchfile 0.07% HTML 0.78% CSS 0.85% JavaScript 0.66% Shell 0.03%
library telegram telegram-api telethon mtproto python-library hacktoberfest

telethon's People

Contributors

9ary avatar andr-04 avatar apepenkov avatar cher-nov avatar expectocode avatar goblenus avatar ingria avatar jeffffc avatar josxa avatar juanpotato avatar kacnep89 avatar kshubham506 avatar kyle2142 avatar lonami avatar manuel1510 avatar new-dev0 avatar nick80835 avatar notafile avatar painor avatar penn5 avatar s3mple avatar seriyps avatar spechide avatar stek29 avatar trifle avatar tulir avatar udf avatar vegeta1k95 avatar vrumger avatar zed avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

telethon's Issues

MessageService error in interactive_telegram_client.py

Hi again,
i found a problem in interactive_telegram_client.py. when you call get_message_history for a group which a user joined recently, you have an error.
for fix this error i add this liens before "if msg.media:" about line 152:

    if isinstance(msg, MessageService):
        continue

Bug in channel and group message id (not in Users)

Hi Dears,
when i take messages with command
total_count, messages, senders = client.get_message_history(entity, limit=10)
and forward received messages , wrong message forwarded!
but in user message (if entity is User) all job's work fine

ValueError: The result of the invoked request is always None

After I switched to the upstream version I got the following error a few times

ValueError: The result of the invoked request is always None

Here is my traceback.

Traceback (most recent call last):
  File "site/rudevs.py", line 29, in <module>
    client.start()
  File "/development/rudevs/chats/telegram/telegram.py", line 105, in start
    self.sync_telegram()
  File "/development/rudevs/chats/telegram/telegram.py", line 100, in sync_telegram
    self.get_content(channels, self.telegram_on_message_callback)
  File "/development/rudevs/chats/telegram/telegram.py", line 62, in get_content
    entity, limit=self.message_count, min_id=entity.min_id)
  File "/development/Telethon/telethon/telegram_client.py", line 363, in get_message_history
    add_offset=add_offset))
  File "/development/Telethon/telethon/telegram_client.py", line 181, in invoke
    return self.invoke(request, timeout, throw_invalid_dc, tries - 1, expect_result)
  File "/development/Telethon/telethon/telegram_client.py", line 181, in invoke
    return self.invoke(request, timeout, throw_invalid_dc, tries - 1, expect_result)
  File "/development/Telethon/telethon/telegram_client.py", line 181, in invoke
    return self.invoke(request, timeout, throw_invalid_dc, tries - 1, expect_result)
  File "/development/Telethon/telethon/telegram_client.py", line 179, in invoke
    raise ValueError('The result of the invoked request is always None')
ValueError: The result of the invoked request is always None

I do not know how exactly to reproduce the error. As I understand it happens if I join new a channel then try to get_history with 30 messages.

Timeout for invoke

We have to implement a timeout in invoke. For example, we lost internet connection just before sending a message; we will trapped in infinite loop in reading receive.

How get users (list) from Supergroup?

How i can get all users from supergroup channel??? GetChannelsRequest, GetAllChatsRequest and GetChatsRequest take Error:
Unknown error message with code 400: CHANNEL_INVALID

Error after trying to download a file from another DC

Hi!
When I attempt to download a media from another DC, rather than on which I logged in, I get an error
Read RPC error: (RPCError(...), 'The file to be accessed is currently stored in a different data center (#X).')
and after an error
Read RPC error: (RPCError(...), 'The key is not registered in the system.')
After which the data no longer come. When i restart and use the session file, the same error occurs about the not registered key. It only helps to delete the session file.

Requests returning vector results are not supported

How to reproduce:
just invoke(ReceivedMessagesRequest(...))
then get:
Traceback (most recent call last):
client.connect()
File "/usr/local/lib/python3.6/site-packages/telethon/telegram_client.py", line 113, in connect
layer=layer, query=query))
File "/usr/local/lib/python3.6/site-packages/telethon/telegram_client.py", line 162, in invoke
self.sender.receive(request, timeout)
File "/usr/local/lib/python3.6/site-packages/telethon/network/mtproto_sender.py", line 143, in receive
request)
File "/usr/local/lib/python3.6/site-packages/telethon/network/mtproto_sender.py", line 223, in process_msg
return self.handle_container(msg_id, sequence, reader, request)
File "/usr/local/lib/python3.6/site-packages/telethon/network/mtproto_sender.py", line 277, in handle_container
if not self.process_msg(inner_msg_id, sequence, reader, request):
File "/usr/local/lib/python3.6/site-packages/telethon/network/mtproto_sender.py", line 218, in process_msg
return self.handle_rpc_result(msg_id, sequence, reader, request)
File "/usr/local/lib/python3.6/site-packages/telethon/network/mtproto_sender.py", line 347, in handle_rpc_result
request.on_response(reader)
File "/usr/local/lib/python3.6/site-packages/telethon/tl/functions/invoke_with_layer.py", line 34, in on_response
self.result = reader.tgread_object()
File "/usr/local/lib/python3.6/site-packages/telethon/utils/binary_reader.py", line 123, in tgread_object
raise TypeNotFoundError(constructor_id)
telethon.errors.TypeNotFoundError: (TypeNotFoundError(...), 'Could not find a matching Constructor ID for the TLObject that was supposed to be read with ID 0x1cb5c415. Most likely, a TLObject was trying to be read when it should not be read.')

Also session becomes completely broken after that and confimation code needs to be sent again

InputPhoneContact does not work

It seems to import the contact phone number does not work.

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Users/we1tkind/.virtualenvs/tg_bot/lib/python3.5/site-packages/telethon/telegram_client.py", line 139, in invoke
    self.sender.send(request)
  File "/Users/we1tkind/.virtualenvs/tg_bot/lib/python3.5/site-packages/telethon/network/mtproto_sender.py", line 103, in send
    self.send_packet(writer.get_bytes(), request)
  File "/Users/we1tkind/.virtualenvs/tg_bot/lib/python3.5/site-packages/telethon/network/mtproto_sender.py", line 154, in send_packet
    self.transport.send(cipher_writer.get_bytes())
  File "/Users/we1tkind/.virtualenvs/tg_bot/lib/python3.5/site-packages/telethon/network/tcp_transport.py", line 32, in send
    self.tcp_client.write(writer.get_bytes())
  File "/Users/we1tkind/.virtualenvs/tg_bot/lib/python3.5/site-packages/telethon/network/tcp_client.py", line 39, in write
    self.socket.sendall(data)
BrokenPipeError: [Errno 32] Broken pipe

Optional sessions store

In my case I use Telethon for many users and I need store sessions in DB.
Maybe sessions storing in files should be optionally?
Thanks.

Better handling of ack requests

Sometimes at any random point in time, an ack request may be received, thus considering the invoked method to be confirmed. This will end the loop that checks whether the result was received yet or not, thus having a None result and failing at random points on the code.

The problem however is that there are some requests which do depend on the ack request to confirm the invoked method, such as the LogoutRequest. How to tell which should be confirmed and which shouldn't doesn't seem trivial, furthermore, this happens randomly (although it is more likely to happen if sending several GetFileRequest's, personal experience).

Maybe one should look into the tdesktop source to check how they handle this kind of stuff.

Odd msg_seqno expected (relevant message), but even received.

I receive telethon.errors.BadMessageError: (BadMessageError(...), 'Odd msg_seqno expected (relevant message), but even received.') when trying to invoke telethon.tl.types.InputChannelEmpty:

result = client.invoke(
InputChannelEmpty()
)
return result

How to join a channel/group?

I need to write a simple script having a function getting channel/group link as input which joins the group/channel and returns a boolean whether the joining was successful or not.

Well, I assume that I don't need update_handler. I just have to do authentication and then without client.run(), I just call the corresponding rpc functions as documented. Am I right?

Can anyone provide an example or something helpful. That would be a big help for me and future readers. Thanks.

Add 2 factor auth

I have enabled 2 factor auth in my telegram and when I tried to login I got this:
RPCError: (RPCError(...), 'Unknown error message with code 401: SESSION_PASSWORD_NEEDED')

Error after several send/receive requests

I've made sending Pong if there's ping in the message body.
message is received in update_handler. Everything is done like in example. Several answers on Ping are send ok, but after that error is raised. What am I doing wrong?

Exception in thread Updates thread:
Traceback (most recent call last):
  File "C:\Python36\lib\threading.py", line 916, in _bootstrap_inner
    self.run()
  File "C:\Python36\lib\threading.py", line 864, in run
    self._target(*self._args, **self._kwargs)
  File "D:\Telethon\Telethon\telethon\network\mtproto_sender.py", line 394, in updates_thread_method
    reader)
  File "D:\Telethon\Telethon\telethon\network\mtproto_sender.py", line 223, in process_msg
    return self.handle_container(msg_id, sequence, reader, request)
  File "D:\Telethon\Telethon\telethon\network\mtproto_sender.py", line 277, in handle_container
    if not self.process_msg(inner_msg_id, sequence, reader, request):
  File "D:\Telethon\Telethon\telethon\network\mtproto_sender.py", line 218, in process_msg
    return self.handle_rpc_result(msg_id, sequence, reader, request)
  File "D:\Telethon\Telethon\telethon\network\mtproto_sender.py", line 339, in handle_rpc_result
    'Cannot receive a request from inside an RPC result from the updates thread.')
ValueError: Cannot receive a request from inside an RPC result from the updates thread.

Please give me a documentation!

Hi Dears,
Thank you for this best project in this section
there is a lot of class with a lot of attributes and a lot of function with a lot of parameter ๐Ÿ˜…
is there a document for help us to realize them?

thanks in advance.

How to add new contacts?

Hi. New in telegram api, i've researched webogram(js web version), so simple question

My goal is to add a bulk list of contacts from file, like .vcf file or phone per line
i've tried InputPhoneContact and ImportContactsRequest but got no expected result. either i send something wrong in these functions

What api calls should i use for this, can you help me please with code snippet?

add getContacts method

i didn`t found the getContacts method and its one of the most important methos
tnx for your time

Don't hardcode server_address in Session

Server IPs are regional and I was getting this first time
RPCError: (RPCError(...), 'The source IP address is associated with a different data center (#4, for registration).')
I created a session object and changed IP address and it worked but it would have been nicer if I could control this from settings.
By the way I suggest json over pickle to serialize session object.

AttributeError: 'NoneType' object has no attribute 'messages'

Got the following error a few times

Traceback (most recent call last):
  File "site/my_app.py", line 109, in <module>
    watch_telegram()
  File "site/my_app.py", line 94, in watch_telegram
    client.get_content(channels, telegram_on_message_callback)
  File "/path/to/my_app/chats/telegram/telegram.py", line 58, in get_content
    entity, limit=self.message_count, min_id=entity.min_id)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/telethon/telegram_client.py", line 340, in get_message_history
    total_messages = getattr(result, 'count', len(result.messages))

AttributeError: 'NoneType' object has no attribute 'messages'

I initialise my example exactly the same as it happens in the InteractiveTelegramClient. The get_content method is an equivalent run. (Basically the same code)

Issues running Telethon for the first time

If it's the first time running Telethon, these are some issues that some people (including me) have had:

  • An exception happens after handling the InvalidDcError, "data is trying to be read outside the bounds".
  • After a "corrupted .session" is created, the same packet is always received: b'l\xfe\xff\xff'.

Both however are solved by deleting the .session file. I don't know what could be causing this. Is b'l\xfe\xff\xff' some Telegram code? What does it mean:

  • b'l\xfe\xff\xff' (little endian) 4294966892 or 0xfffffe6c
  • b'l\xfe\xff\xff' (big endian) 1828651007 or 0x6cfeffff

Infinite loop in TcpClient.read after about 1 hour of running

After about one hour after start of TelegramClient its updates_thread falls in infinite loop,
TcpClient module, lines 58-70.
self.socket.recv(left_count) each time returns 0 bytes,
buffer_size = 4
left_count = 4
partial = b''

Thread utilizing full cpu core and doesn't process any next updates.
Bug is reproducing each time, without exceptions.

Simple python script which reproduced bug (in sessionid.session stored valid session):

from telethon import TelegramClient
from time import sleep


def update_handler(update_object):
    print(update_object)

tg = TelegramClient('sessionid', api_id=00000, api_hash='********************************')
tg.connect()
tg.add_update_handler(update_handler)

while True:
    sleep(0.1)

Tested on Ubuntu 16.04.2 LTS, Python 3.5.2, Telethon 0.7.0.1, pyaes 1.6.0

[Q] How to add user to supergroup with userid

Hello,

I want to add user(s) to existing supergroup that I created(have admin privileges).
How can I add user with resolved userid into supergroup?

First I tried AddChatUserRequest but failed. According to #38, supergroup was treated as channel. So I did not try AddChatUserRequest API, will be 400 CHAT_ID_INVALID.

Next I tried InviteToChannelRequest but does not work for supergroup.
(Case1) add user to supergroup by InviteToChannelRequest API(fail, server returns 400 PEER_FLOOD)
(Case2) add user to channel by InviteToChannelRequest API(Succeeded)

Is it right way to use InviteToChannelRequest to add user to supergroup? Or any invalid parameter?
Added code to client "telegram_client.py":

`
def add_user(self,
user_id, # by SearchRequest, int ex. 230000000
user_access_hash, # by SearchRequest, long ex. 2000000000000000000
entity): # by get_dialogs

if type(entity) is Chat:
    print("chat. try AddChatUserRequest")
    return
print(entity)
print()

chat_id = entity.id  # ex. id=1113800000
inuser = InputUser(user_id, user_access_hash)
chan = InputChannel(chat_id, entity.access_hash)

if hasattr(entity, "megagroup") and entity.megagroup: # debug code
    # (Case1) not work(400 PEER_FLOOD)
    print("Here is supposed to be supergroup!")
try:
    print("InviteToChannelRequest:")
    result = self.invoke(InviteToChannelRequest(chan, [inuser]))
    print(result)
except RPCError as err:
    print("telethon.errors.RPCError Detected: {0}".format(err))

`

Increase get_dialogs limit

Hello agian,
i tried to get_dialogs(200) but it limit on 99 and not show more, how i can get more?
tank you

New method for saving Session

Pickle is good for starting but not for long run, JSON is better for human readability, config file is good for centralized configuration and readability, sqlite db is good for future when storing more data is necessary, each has its pros and cons and best method for this project needs to be discussed.

[Q] How to forward a message?

Hello, I wanna forward a message from a channel to a group. I found ForwardMessageRequest class. My question is:
How pass id parameter to this class? I mean how can i get id of a message in group?

I tested this:

for msg in messages:
    try:
        msg.message
        msg_id = utils.generate_random_long()
        client.invoke(ForwardMessageRequest(peer=get_input_peer(Entity), id=msg.id, random_id=msg_id))
    except:
        pass

But when i run script it says:
Could not stabilise initial connection: (RPCError(...), 'Unknown error message with code 400: MESSAGE_ID_INVALID')

Error in get_message_history

Hi, I occasionally get this error in get_message_history method:

[2017-03-03 12:16:44] ERROR [utils:utils.py:log_exception:77] 'NoneType' object has no attribute 'messages'
Traceback (most recent call last):
  File "/home/k1/src/bot/bot.py", line 174, in loop
    method['method']()
  File "/home/k1/src/bot/bot.py", line 183, in detele_old_messages
    message_history = self.client_api.get_message_history(bot, config.TELEGRAM['cleanup_messages'])
  File "/home/k1/.virtualenv/bot/lib/python3.5/site-packages/telethon/telegram_client.py", line 340, in get_message_history
    total_messages = getattr(result, 'count', len(result.messages))
AttributeError: 'NoneType' object has no attribute 'messages'

Locals

{
'add_offset': '0',
'entity': 'user#d10d979a flags:None '
          'is_self:flags.10?true '
          'contact:flags.11?true '
          'mutual_contact:flags.12?true '
          'deleted:flags.13?true '
          'bot:flags.14?true '
          'bot_chat_history:flags.15?true '
          'bot_nochats:flags.16?true '
          'verified:flags.17?true '
          'restricted:flags.18?true '
          'min:flags.20?true '
          'bot_inline_geo:flags.21?true '
          'id:int access_hash:flags.0?long '
          'first_name:flags.1?string '
          'last_name:flags.2?string '
          'username:flags.3?string '
          'phone:flags.4?string '
          'photo:flags.5?UserProfilePhoto '
          'status:flags.6?UserStatus '
          'bot_info_version:flags.14?int '
          'restriction_reason:flags.18?string '
          'bot_inline_placeholder:flags.19?string '
          '= User',
'limit': '20',
'max_id': '0',
'min_id': '0',
'offset_date': 'None',
'offset_id': '0',
'result': 'None',
'self': '<telethon.interactive_telegram_client.InteractiveTelegramClient '
'object at 0x7f4225ec4a90>'
}

Raise 'RPC results should only happen after a request was sent'

I sometimes get this raise 'RPC results should only happen after a request was sent' called from updates_thread_method in mtproto_sender.py

This raise when I call send_message couple or more times (say from a list) without a delay. What do you suggest.

RPCError(...), 'The api_id/api_hash combination is invalid.'

When I run python3 try_telethon.py it all the time says

RPCError(...), 'The api_id/api_hash combination is invalid.'

OS: MacOS, Ubuntu 12.04.

It even does not want to connect. The error occurs on the first self.connect call (Could not stabilise initial connection). What is worth, occasionally this call works. But all the time it fails on sending a code (SendCodeRequest). I use 2 different telegram accounts. The result is the same.

I do as it's written in the readme:

  • Run the tl_generator.py
  • Create and edit the settings
  • python3 try_telethon.py

I get the same result in case of using an installed through the pip version.

Could you please tell, if I should do something else.

Update

When the connect call works, it returns the following

(config (ID: 0x3af6fb5f) = (phonecalls_enabled=None, date=2017-04-07 11:43:30, expires=1491558606, test_mode=False, this_dc=5, dc_options=['(dcOption (ID: 0x5d8c6cc) = (ipv6=None, media_only=None, tcpo_only=None, id=1, ip_address=149.154.175.50, port=443))', '(dcOption (ID: 0x5d8c6cc) = (ipv6=True, media_only=None, tcpo_only=None, id=1, ip_address=2001:0b28:f23d:f001:0000:0000:0000:000a, port=443))', '(dcOption (ID: 0x5d8c6cc) = (ipv6=None, media_only=None, tcpo_only=None, id=2, ip_address=149.154.167.51, port=443))', '(dcOption (ID: 0x5d8c6cc) = (ipv6=True, media_only=None, tcpo_only=None, id=2, ip_address=2001:067c:04e8:f002:0000:0000:0000:000a, port=443))', '(dcOption (ID: 0x5d8c6cc) = (ipv6=None, media_only=None, tcpo_only=None, id=3, ip_address=149.154.175.100, port=443))', '(dcOption (ID: 0x5d8c6cc) = (ipv6=True, media_only=None, tcpo_only=None, id=3, ip_address=2001:0b28:f23d:f003:0000:0000:0000:000a, port=443))', '(dcOption (ID: 0x5d8c6cc) = (ipv6=None, media_only=None, tcpo_only=None, id=4, ip_address=149.154.167.91, port=443))', '(dcOption (ID: 0x5d8c6cc) = (ipv6=True, media_only=None, tcpo_only=None, id=4, ip_address=2001:067c:04e8:f004:0000:0000:0000:000a, port=443))', '(dcOption (ID: 0x5d8c6cc) = (ipv6=None, media_only=True, tcpo_only=None, id=4, ip_address=149.154.165.120, port=443))', '(dcOption (ID: 0x5d8c6cc) = (ipv6=None, media_only=None, tcpo_only=None, id=5, ip_address=91.108.56.165, port=443))', '(dcOption (ID: 0x5d8c6cc) = (ipv6=True, media_only=None, tcpo_only=None, id=5, ip_address=2001:0b28:f23f:f005:0000:0000:0000:000a, port=443))'], chat_size_max=200, megagroup_size_max=5000, forwarded_count_max=100, online_update_period_ms=120000, offline_blur_timeout_ms=5000, offline_idle_timeout_ms=30000, online_cloud_timeout_ms=300000, notify_cloud_delay_ms=30000, notify_default_delay_ms=1500, chat_big_size=10, push_chat_period_ms=60000, push_chat_limit=2, saved_gifs_limit=200, edit_time_limit=172800, rating_e_decay=2419200, stickers_recent_limit=30, tmp_sessions=None, pinned_dialogs_count_max=5, call_receive_timeout_ms=20000, call_ring_timeout_ms=90000, call_connect_timeout_ms=30000, call_packet_timeout_ms=10000, disabled_features=None))

can not encode to utf-8

hi when i call the "get_dialogs" return an error:

Traceback (most recent call last):
File "/usr/lib/python3.5/threading.py", line 914, in _bootstrap_inner
self.run()
File "/usr/lib/python3.5/threading.py", line 862, in run
self._target(*self._args, **self._kwargs)
File "/usr/local/lib/python3.5/dist-packages/telethon/network/mtproto_sender.py", line 394, in updates_thread_method
reader)
File "/usr/local/lib/python3.5/dist-packages/telethon/network/mtproto_sender.py", line 225, in process_msg
return self.handle_gzip_packed(msg_id, sequence, reader, request)
File "/usr/local/lib/python3.5/dist-packages/telethon/network/mtproto_sender.py", line 356, in handle_gzip_packed
request)
File "/usr/local/lib/python3.5/dist-packages/telethon/network/mtproto_sender.py", line 243, in process_msg
return self.handle_update(msg_id, sequence, reader)
File "/usr/local/lib/python3.5/dist-packages/telethon/network/mtproto_sender.py", line 253, in handle_update
tlobject = reader.tgread_object()
File "/usr/local/lib/python3.5/dist-packages/telethon/utils/binary_reader.py", line 128, in tgread_object
result.on_response(self)
File "/usr/local/lib/python3.5/dist-packages/telethon/tl/types/updates_tg.py", line 64, in on_response
users_item = reader.tgread_object()
File "/usr/local/lib/python3.5/dist-packages/telethon/utils/binary_reader.py", line 128, in tgread_object
result.on_response(self)
File "/usr/local/lib/python3.5/dist-packages/telethon/tl/types/user.py", line 168, in on_response
self.last_name = reader.tgread_string()
File "/usr/local/lib/python3.5/dist-packages/telethon/utils/binary_reader.py", line 92, in tgread_string
return str(self.tgread_bytes(), encoding='utf-8')
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xae in position 6: invalid start byte

i check this problem and i found the "ยฎ" character in a user name.
i'll trying to resolve this problem and commit it

on message receive event

Hello, Is there any method for "on messege receive" event?
I need something like this:

def my_func(sender, msg):
    pass 
client = TelegramClient(...)
client.connect()
client.on_msg_receive(my_func)

[Q] How to delete a message

Using API is so hard, can you help me remove a message using client? I have chat id and message id but I don't know how to use it. Delete message seems only accept a 4 digit number but I don't know what extactly I should put there
https://core.telegram.org/method/messages.deleteMessages

I do this and I don't know what it does

In [117]: z = client.invoke(messages.delete_messages.DeleteMessagesRequest([2887]))

In [118]: z
Out[118]: messages.affectedMessages#84d19185 pts:int pts_count:int = messages.AffectedMessages

No messages recieved

In supergroups, large groups, private chats with inline bot results and sometimes even dialog with bots - I get only telethon.tl.types.updates_tg.UpdatesTg or telethon.tl.types.update_short.UpdateShort and no messages. I thought that I should do something with UpdatesTg, but all that is visiable outside is

__module__
__doc__
constructor_id
__init__
on_send
empty
on_response
__repr__
__str__

What should I do to get all reveived messages? Should I modify that autogenerated Updates_Tg.py file?

Message received acknowledge

I successfully try interactive_telegram_client, but I noted that client never send acknowledge for read status (double check sign).

How do I achieve that ?.

cant get all dialogs with loop

Hi
i need to get all my dialogs with client.get_dialogs()
i tried to get there but unfortunately i couldn't

my code is :

entity = client.get_dialogs(count=100,offset_id=0)
print(entity[1][0].id)
entities=list()
for i in range(5):
    for i in range(len(entity[1])):
        if entity[1][i].id not in entities:
            entities.append(entity[1][i].id)
    try:
        entity = client.get_dialogs(count=100,offset_id=entity[1][-1].id)
        print(entity[1][0].id)
    except:
        print("None Result ...")

print(len(entities))

print('Dialogs loaded.')

but it give None in return for 2nd loop and after that
i get at most 102 dialogs

i have 600 active dialogs now
i`ll be thankful if you give me a sample code for that

Can't decode packet (b'l\xfe\xff\xff')

I get Can't decode packet (b'l\xfe\xff\xff') after running:

client = TelegramClient(session_file, api_id=000, api_hash='XXX')
client.connect()

my code stops here. When I Ctrl+C here is the output:

Traceback (most recent call last):
  File "/root/anaconda3/lib/python3.5/threading.py", line 914, in _bootstrap_inner
    self.run()
  File "/root/anaconda3/lib/python3.5/threading.py", line 862, in run
    self._target(*self._args, **self._kwargs)
  File "kim.py", line 122, in connect_to_telegram
    client.connect()
  File "/root/anaconda3/lib/python3.5/site-packages/telethon/telegram_client.py", line 118, in connect
    layer=layer, query=query))
  File "/root/anaconda3/lib/python3.5/site-packages/telethon/telegram_client.py", line 175, in invoke
    self.sender.receive(request, timeout)
  File "/root/anaconda3/lib/python3.5/site-packages/telethon/network/mtproto_sender.py", line 135, in receive
    message, remote_msg_id, remote_sequence = self.decode_msg(body)
  File "/root/anaconda3/lib/python3.5/site-packages/telethon/network/mtproto_sender.py", line 186, in decode_msg
    raise BufferError("Can't decode packet ({})".format(body))
BufferError: Can't decode packet (b'l\xfe\xff\xff')

This happens for one of my SIMs.

self in update_handler? (i need send_message, delete_messages etc, from update_handler).

Hi all, sorry for my bad english and lame code))) Can you help me, show example code, for automate answer message or do some...

i edit interactive_telegram_client.py in def update_handler(update_object) add new types check

elif type(update_object) is UpdatesTg:
    for update in update_object.updates:
        if type(update) is UpdateNewChannelMessage:
            if update.message.message:
                print('[SuperGroup: {}]'.format(update.message.message))

it work fine. But how i can use example, some like this:

elif type(update_object) is UpdatesTg:
    for update in update_object.updates:
        if type(update) is UpdateNewChannelMessage:
            if update.message.message:
                self.send_message(1062677923, " MESSAGES TEST ")

how send "self" in def update_handler(update_object): or any another way for this do?

An app does not receive any updates after several hours of work

My app subscribes for updates using self.add_update_handler. It works fine, but after about 5 hours of working it stops receiving updates (according to the web interface there are updates). My log.


DEBUG:root:Handling update for object updates_tg#74ae4240 updates:Vector<Update> users:Vector<User> chats:Vector<Chat> date:date seq:int = Updates
Update was received
DEBUG:root:Handling update for object updates_tg#74ae4240 updates:Vector<Update> users:Vector<User> chats:Vector<Chat> date:date seq:int = Updates
Update was received
DEBUG:root:Handling update for object updates_tg#74ae4240 updates:Vector<Update> users:Vector<User> chats:Vector<Chat> date:date seq:int = Updates
Update was received
INFO:root:Trying to .receive() the request result...
DEBUG:root:Handling container
DEBUG:root:Handling update for object updates_tg#74ae4240 updates:Vector<Update> users:Vector<User> chats:Vector<Chat> date:date seq:int = Updates
Update was received
DEBUG:root:Handling update for object updates_tg#74ae4240 updates:Vector<Update> users:Vector<User> chats:Vector<Chat> date:date seq:int = Updates
Update was received
INFO:root:Trying to .receive() the request result...
DEBUG:root:Handling update for object updates_tg#74ae4240 updates:Vector<Update> users:Vector<User> chats:Vector<Chat> date:date seq:int = Updates
Update was received
INFO:root:Trying to .receive() the request result...
DEBUG:root:Handling update for object updates_tg#74ae4240 updates:Vector<Update> users:Vector<User> chats:Vector<Chat> date:date seq:int = Updates
INFO:root:Trying to .receive() the request result...
DEBUG:root:Handling pong
WARNING:root:Pong confirmed a request
INFO:root:Request result received
DEBUG:root:receive() released the lock
DEBUG:root:Ping sent from the updates thread
DEBUG:root:Trying to receive updates from the updates thread
DEBUG:root:Receiving updates timed out
DEBUG:root:Updates thread released the lock
DEBUG:root:Updates thread acquired the lock
DEBUG:root:send() acquired the lock
DEBUG:root:send() released the lock
DEBUG:root:receive() acquired the lock
INFO:root:Trying to .receive() the request result...
DEBUG:root:Receiving updates timed out
DEBUG:root:Updates thread released the lock

Unable to detect exceptions in Updates thread

Sometimes an exception in Updates thread is raised for unknown reason (happens accidentially)

For example:
Exception in thread Updates thread:
Traceback (most recent call last):
File "/usr/local/Cellar/python3/3.6.0/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py", line 916, in _bootstrap_inner
self.run()
File "/usr/local/Cellar/python3/3.6.0/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py", line 864, in run
self._target(*self._args, **self._kwargs)
File "/usr/local/lib/python3.6/site-packages/telethon/network/mtproto_sender.py", line 394, in updates_thread_method
reader)
File "/usr/local/lib/python3.6/site-packages/telethon/network/mtproto_sender.py", line 218, in process_msg
return self.handle_rpc_result(msg_id, sequence, reader, request)
File "/usr/local/lib/python3.6/site-packages/telethon/network/mtproto_sender.py", line 339, in handle_rpc_result
'Cannot receive a request from inside an RPC result from the updates thread.')
ValueError: Cannot receive a request from inside an RPC result from the updates thread.

There are many different exceptions potentially could be raised in mtproto_sender.py , so it probably would be great to have an easy way to detect this someway from main thread to allow reconnect.

Thanks.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.