alexander-akhmetov / python-telegram Goto Github PK
View Code? Open in Web Editor NEWPython client for the Telegram's tdlib
License: MIT License
Python client for the Telegram's tdlib
License: MIT License
Hi!
Thanks for this awesome project! Can you please explain to me how to change auto download settings or to download any file manually? Also, can I manually delete downloaded file using
rm $some_tg_downloaded_file
?
Again big thanks,
Andrew Ishutin
P. S. Should I open this issue in the TDLib repo?
> tg._tdjson.stop()
*** AttributeError: dlsym(0x7fac0dd74cb0, _td_json_client_destroy): symbol not found
I am trying to use python-telegram on a Raspberry Pi which has a 32-bit core. I loaded python-telegram using the command:
`python3 -m pip install python-telegram`
When I run the tutorial I get this error:
`lib/python3.6/site-packages/telegram/lib/linux/libtdjson.so: wrong ELF class: ELFCLASS64`
How do I get a 32-bit version of the libs?
Add additional checks: flake8
, isort
, mypy
and py37
Hi. In tdlib repo, it is mentioned that "The wrapper uses the full power of asyncio" . But is it true?
In the TDLIB update event, there is only the 'sender_user_id' field and no other user identification. Currently, there is no way to get first and last names using python-telegram.
As far as I know, to get that information the client should use getUserFullInfo() method. Please, add it.
Couldn't find how to create a new group programmatically in the documentation. Kindly help me with it.
Hey since the tdlib library in the project is outdated, I would like compile the newest (1.5) version. But I don't know how, since there are several options...Could you tell me the command how you compiled the lib?
Hey, currently its not possible to send images or? Do you know if its possible with tdlib?
Traceback (most recent call last):
File "core.py", line 21, in
default_workers_queue_size = 1000,
File "/usr/local/lib/python3.6/dist-packages/telegram/client.py", line 96, in init
self._tdjson = TDJson(library_path=library_path, verbosity=tdlib_verbosity)
File "/usr/local/lib/python3.6/dist-packages/telegram/tdjson.py", line 27, in init
self._build_client(library_path, verbosity)
File "/usr/local/lib/python3.6/dist-packages/telegram/tdjson.py", line 36, in _build_client
self._tdjson = CDLL(library_path)
File "/usr/lib/python3.6/ctypes/init.py", line 348, in init
self._handle = _dlopen(self._name, mode)
OSError: /usr/lib/x86_64-linux-gnu/libcrypto.so.1.1: version `OPENSSL_1_1_1' not found (required by /usr/local/lib/python3.6/dist-packages/telegram/lib/linux/libtdjson.so)
hello guys how to fix this? :(
Hi,
I am trying to build a telegram-client with this library, that does not get its inputs from stdin. Unfortunately Telegram.login()
asks the confirmation code from the standard input. Is it possible to relay the code in any other matter?
Like one call to start the process of obtaining the code, and a call to another function to verify it. This way it would allow me to forward the request to the UI.
Another thing I noticed is that by using the library I have a lot of output in my stdout. This seems to be some kind of debug mode. Is it possible to run it outside of a debug mode?
Exception in thread Thread-1:
Traceback (most recent call last):
File "/usr/lib/python3.6/threading.py", line 916, in _bootstrap_inner
self.run()
File "/usr/lib/python3.6/threading.py", line 864, in run
self._target(*self._args, **self._kwargs)
File "/usr/local/lib/python3.6/dist-packages/telegram/client.py", line 396, in _listen_to_td
self._run_handlers(update)
File "/usr/local/lib/python3.6/dist-packages/telegram/client.py", line 427, in _run_handlers
self._workers_queue.put((handler,update),timeout=self._queue_put_timeout)
File "/usr/lib/python3.6/queue.py", line 141, in put
raise Full
queue.Full
hello guys
how i can fix this and how i can work by many worker ?
Hello. I found a bag in source code of telegram.Telegram class!
In some cases, when using client's "call_method" function the returned async_result will never refresh. No errors, no updates. Just stacked in .wait() state. I have found decision. Just swap two lines in "_send_data" method of telegram.Telegram class.
def _send_data(
self, data: Dict[Any, Any], result_id: Optional[str] = None
) -> AsyncResult:
if '@extra' not in data:
data['@extra'] = {}
if not result_id and 'request_id' in data['@extra']:
result_id = data['@extra']['request_id']
async_result = AsyncResult(client=self, result_id=result_id)
data['@extra']['request_id'] = async_result.id
self._tdjson.send(data)
self._results[async_result.id] = async_result
async_result.request = data
return async_result
def _send_data(
self, data: Dict[Any, Any], result_id: Optional[str] = None
) -> AsyncResult:
if '@extra' not in data:
data['@extra'] = {}
if not result_id and 'request_id' in data['@extra']:
result_id = data['@extra']['request_id']
async_result = AsyncResult(client=self, result_id=result_id)
async_result.request = data
data['@extra']['request_id'] = async_result.id
self._results[async_result.id] = async_result # Поменял эти две строчки местами
self._tdjson.send(data) # И все стало работать нормально...
return async_result
Hey I tried to handle the flooded error and followed this example](https://github.com/alexander-akhmetov/python-telegram/blob/91d577e75f7dbfe022fe9085f2a7bacef6712ee2/examples/send_message.py)
I tested it by looping the send_message function 300 times. I could sent 250 messages but than I got this error: "Error: 429 : Too Many Requests: retry after 19"
But still all the time result.error was False.
Hello,
I am using echo_bot.py for getting messaging. I am getting sender_id = 0 in case channel thread and also chat_id negative number but it works fine in case of normal user thread can someone help or fix this issue, please.
Currently there are some functions (get_me(), get_chat(), get_chats(), ...) implemented in client.py, some functions can be called via the call_method() function.
How do you plane to have this in the future? do you want to have all functions implemented?
maybe split up in two py-files: one for functions which can be used for the bot, the other one for normal API functions.
I could give you a hand with this.
File "/app/index.py", line 17, in
tg.login()
File "/usr/local/lib/python3.8/site-packages/telegram/client.py", line 439, in login
result.wait(raise_exc=True)
File "/usr/local/lib/python3.8/site-packages/telegram/utils.py", line 41, in wait
raise RuntimeError(f'Telegram error: {self.error_info}')
RuntimeError: Telegram error: {'@type': 'error', 'code': 400, 'message': 'Failed to parse JSON object as TDLib request: Wrong padding length', '@extra': {'request_id': 'updateAuthorizationState'}}
Code is running in docker!
Thank you
is it possible to provide my own version of openssl? i've installed via pip3 and it seems that libtdjson
requires right only libssl.1.0.0
, while there's libssl.1.1
available on my system
Hi all,
I am trying to fetch messages from a bunch of public channels and eventually start hitting "FLOOD_WAIT_" errors.
Do you mind sharing what is the best way to catch those errors (so that script pauses sending requests)?
Thank you.
Hello,
I play with master branch of python-telegram and found a bug. When I try to set my first/last name then AsyncResult wait forever. It happens because Event self._ready.set() in the AsyncResult is set only if update @type != 'ok'
.
I guess it was made for login purposes where result @type='ok'
is not means that result is ready.
This is my code:
tg.login()
result = tg.get_me()
result.wait()
print(result.update)
logger.debug("Setting name")
result = tg.call_method('setName', params={'first_name': 'First', 'last_name': 'Last'})
result.wait() # there it waits forever
print(result.update)
I changed the parse_update
method of AsyncResult as follows by adding condition if self.id != 'updateAuthorizationState'
and it start working.
def parse_update(self, update: Dict[Any, Any]) -> None:
if update.get('@type') == 'ok':
self.ok_received = True
# added following 3 lines
if self.id != 'updateAuthorizationState':
self._ready.set()
return True
return False
if update.get('@type') == 'error':
self.error = True
self.error_info = update
else:
self.update = update
self._ready.set()
return True
But I not 100% sure that my way is correct, I just started to play with Telegram lib a day ago..
hey im using td 1.5.1 , python 3.7
data = {
'@type': 'checkChatInviteLink',
'invite_link ': link,
}
res = tg._send_data(data)
res.wait()
print(res.error_info)
prints :
{'@type': 'error', 'code': 3, 'message': 'Wrong invite link', '@extra': {'request_id': 'a3a0b4dcd9fb401bb4dcfdecc36425a1'}}
i test many links
but i got same error.
There is 1.3.0
already: https://github.com/tdlib/td/releases/tag/v1.3.0
Right now it is required to specify update type, but it would be great to subscribe to all updates
Hello,
so I want to set the Online Status to online for using secret chats.
Therefore I firstly call the setOption function (link: https://core.telegram.org/tdlib/docs/classtd_1_1td__api_1_1set_option.html) as described in this issue from TDlib tdlib/td#714.
I'm using the newest version of TDlib (compiled by my own)
So my code after login:
### Yomam
tg = Telegram(
api_id=XXXX,
api_hash=XXXX,
phone=XXXX,
database_encryption_key=XXXX,
library_path="XXXX/tdlib/lib/libtdjson.so.1.5.4"
)
tg.login()
#Set online status
data = {
'@type': 'setOption',
'name': 'online',
'value': {
'@type': 'optionValueBoolean',
'value': True,
},
}
result = tg._send_data(data)
result.wait()
print(result.update)
result = tg.call_method("getOption", params={'name':'online'})
result.wait()
print(result.update)
tg.idle()
Output is:
...
XXXX [INFO] telegram.client: Completing auth process
And then it hangs...
So any ideas how to handle this?
hello why edited message not have result?
There are no limits for message queues and results:
Message queues
telegram.client.Telegram._queue
python-telegram/telegram/client.py
Line 69 in 80b2619
telegram.client.Telegram._workers_queue
python-telegram/telegram/client.py
Line 71 in 80b2619
Results dictionary
telegram.client.Telegram._results
python-telegram/telegram/client.py
Line 76 in 80b2619
Hello!
I'm trying to get my chats but receiving empty chat_ids
list.
tg = Telegram(
api_id=API_ID,
api_hash=API_HASH,
database_encryption_key='',
library_path=PATH_TO_LIBTDJSON,
phone=MY_PHONE
)
tg.login()
result = tg.get_chats()
result.wait()
print(result.update)
The result is
{'@type': 'chats', 'chat_ids': [], '@extra': {'request_id': 'acf2ec5fe1e442b0b507efd0687028ac'}}
What I'm doing wrong ?
Traceback (most recent call last):
File "pytele.py", line 7, in
database_encryption_key='mahesh',
File "C:\Users\Asus\AppData\Local\Programs\Python\Python36\lib\site-packages\telegram\client.py", line 81, in init
library_path=library_path,
File "C:\Users\Asus\AppData\Local\Programs\Python\Python36\lib\site-packages\telegram\tdjson.py", line 37, in init
self._build_client(library_path)
File "C:\Users\Asus\AppData\Local\Programs\Python\Python36\lib\site-packages\telegram\tdjson.py", line 40, in _build_client
self.tdjson = CDLL(library_path)
File "C:\Users\Asus\AppData\Local\Programs\Python\Python36\lib\ctypes_init.py", line 348, in init
self._handle = _dlopen(self._name, mode)
OSError: [WinError 193] %1 is not a valid Win32 application
Getting this
OSError: libc.musl-x86_64.so.1: cannot open shared object file: No such file or directory
with tutorial example on Ubuntu 16.04
Regular class initialization
client = Telegram(
api_id=self.api_id,
api_hash=self.api_hash,
library_path=self.library_path,
phone='+XXXXXXXXXXXX'',
database_encryption_key='XXXXXXXXXXX',
use_test_dc=True,
files_directory=self.files_directory,
use_message_database=False,
login=True,
)
Randomly causes an error
Telegram error: {'@type': 'error', 'code': 401, 'message': 'Database encryption key is needed: call checkDatabaseEncryptionKey first', '@extra': {'request_id': 'updateAuthorizationState'}}
Next time you start everything can work fine
INFO:telegram.tdjson:Using shared library "/app/telegram_data/vendor/tdlib/libtdjson.so"
INFO:telegram.client:[Telegram.td_listener] started
INFO:telegram.worker:[SimpleWorker] started
INFO:telegram.client:[login] Login process has been started
INFO:telegram.client:[login] current authorization state: None
INFO:telegram.client:Setting tdlib initial params: files_dir=/app/telegram_data/data/ test_dc=True
DEBUG:telegram.tdjson:[me ==>] Sent b'{"@type": "setTdlibParameters", "parameters": {"use_test_dc": true, "api_id": API_ID, "api_hash": "API_HASH", "device_model": "python-telegram", "system_version": "unknown", "application_version": "0.7.0", "system_language_code": "en", "database_directory": "/app/telegram_data/data/database", "use_message_database": false, "files_directory": "/app/telegram_data/data/files"}, "@extra": {"request_id": "updateAuthorizationState"}}'
DEBUG:telegram.tdjson:[me <==] Received {'@type': 'updateAuthorizationState', 'authorization_state': {'@type': 'authorizationStateWaitTdlibParameters'}}
DEBUG:telegram.tdjson:[me <==] Received {'@type': 'updateAuthorizationState', 'authorization_state': {'@type': 'authorizationStateWaitEncryptionKey', 'is_encrypted': True}}
DEBUG:telegram.client:async_result has not been found in by request_id=updateAuthorizationState
DEBUG:telegram.tdjson:[me <==] Received {'@type': 'ok', '@extra': {'request_id': 'updateAuthorizationState'}}
DEBUG:telegram.client:async_result has not been found in by request_id=updateAuthorizationState
INFO:telegram.client:[login] current authorization state: authorizationStateWaitTdlibParameters
INFO:telegram.client:Setting tdlib initial params: files_dir=/app/telegram_data/data/ test_dc=True
DEBUG:telegram.tdjson:[me ==>] Sent b'{"@type": "setTdlibParameters", "parameters": {"use_test_dc": true, "api_id": API_ID, "api_hash": "API_HASH", "device_model": "python-telegram", "system_version": "unknown", "application_version": "0.7.0", "system_language_code": "en", "database_directory": "/app/telegram_data/data/database", "use_message_database": false, "files_directory": "/app/telegram_data/data/files"}, "@extra": {"request_id": "updateAuthorizationState"}}'
DEBUG:telegram.tdjson:[me <==] Received {'@type': 'error', 'code': 401, 'message': 'Database encryption key is needed: call checkDatabaseEncryptionKey first', '@extra': {'request_id': 'updateAuthorizationState'}}
Traceback (most recent call last):
File "manage.py", line 15, in <module>
execute_from_command_line(sys.argv)
File "/usr/local/lib/python3.7/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line
utility.execute()
File "/usr/local/lib/python3.7/site-packages/django/core/management/__init__.py", line 375, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/usr/local/lib/python3.7/site-packages/django/core/management/base.py", line 316, in run_from_argv
self.execute(*args, **cmd_options)
File "/usr/local/lib/python3.7/site-packages/django/core/management/base.py", line 353, in execute
output = self.handle(*args, **options)
File "/app/telegram_data/management/commands/test.py", line 38, in handle
login=True,
File "/usr/local/lib/python3.7/site-packages/telegram/client.py", line 90, in __init__
self.login()
File "/usr/local/lib/python3.7/site-packages/telegram/client.py", line 339, in login
result.wait(raise_exc=True)
File "/usr/local/lib/python3.7/site-packages/telegram/utils.py", line 39, in wait
raise RuntimeError(f'Telegram error: {self.error_info}')
RuntimeError: Telegram error: {'@type': 'error', 'code': 401, 'message': 'Database encryption key is needed: call checkDatabaseEncryptionKey first', '@extra': {'request_id': 'updateAuthorizationState'}}
I could not run any of the example files because of this error: libtdjson.so: invalid ELF header
.
These are the steps I did to install python-telegram: I could install and use it correctly a few months ago.
$ cd /tmp
$ git clone https://github.com/alexander-akhmetov/python-telegram.git
$ cd python-telegram/
$ python -m pip install --user .
$ python examples/get_me.py [MY-APP-ID] [MY-APP-HASH] [MY_TELEPHONE-NUMBER]
Traceback (most recent call last):
File "examples/get_me.py", line 16, in <module>
database_encryption_key='changeme1234',
File "/MY-HOME/.local/lib/python3.6/site-packages/telegram/client.py", line 103, in __init__
self._tdjson = TDJson(library_path=library_path, verbosity=tdlib_verbosity)
File "/MY-HOME/.local/lib/python3.6/site-packages/telegram/tdjson.py", line 27, in __init__
self._build_client(library_path, verbosity)
File "/MY-HOME/.local/lib/python3.6/site-packages/telegram/tdjson.py", line 36, in _build_client
self._tdjson = CDLL(library_path)
File "/usr/lib/python3.6/ctypes/__init__.py", line 348, in __init__
self._handle = _dlopen(self._name, mode)
OSError: /MY-HOME/.local/lib/python3.6/site-packages/telegram/lib/linux/libtdjson.so: invalid ELF header
I tried to increase tdlib_verbosity
to 10 but I get no output back.
My environment:
$ uname -a
Linux 4.15.0-65-generic #74-Ubuntu SMP Tue Sep 17 17:06:04 UTC 2019 x86_64 x86_64 x86_64 GNU/Linux
$ lsb_release -a
LSB Version: core-9.20160110ubuntu0.2-amd64:core-9.20160110ubuntu0.2-noarch:printing-9.20160110ubuntu0.2-amd64:printing-9.20160110ubuntu0.2-noarch:security-9.20160110ubuntu0.2-amd64:security-9.20160110ubuntu0.2-noarch
Distributor ID: Ubuntu
Description: Ubuntu 18.04.1 LTS
Release: 18.04
Codename: bionic
I tried with the manually compiled tdlib (version 1.5) and it works perfectly.
Hi
The if condition in _run_handlers
is creating issues, when I try to test tgvoip example. I modified it as
def _run_handlers(self, update: Dict[Any, Any]) -> None:
if update.get('@type') == 'updateNewMessage':
for handler in self._message_handlers:
self._workers_queue.put(
(handler, update),
timeout=self._queue_put_timeout,
)
else:
for handler in self._message_handlers:
self._workers_queue.put(
(handler, update),
timeout=self._queue_put_timeout,
)
or we can create another method for add_message_handler
like add_call_handler
and append functions to new list like _call_handler. In else condition use it.
If ok, I can create a PR.
I can run the ping pong example but i can not receive chat ids.
from telegram.client import Telegram
tg = Telegram(
api_id='0123455',
api_hash='blablabla',
phone='00491766822222', # you can pass 'bot_token' instead
database_encryption_key='changekey123',
)
tg.login()
# if this is the first run, library needs to preload all chats
# otherwise the message will not be sent
result = tg.get_chats()
result.wait()
print(result.update)
This is the result:
{'@type': 'chats', 'chat_ids': [], '@extra': {'request_id': 'd8acbe24880e4385a8a7ce8b79a2bbda'}}
Any idea how to solve this?
[ 1][t 1][1553186089.422070026][MessagesManager.cpp:21569][!Td] Have full history in chat -1001081163428, but receive unknown server message 322600 from get history. Last new is server message 326099, last is server message 319292, first database is server message 1, last database is server message 319292, last read inbox is server message 326099, last read outbox is server message 326099, last read all mentions is invalid message 0, max unavailable is invalid message 0, last assigned is invalid message 0
hello
my bot print this error and change status to offline
how i can fix this problem :(
hello how i can fix stop method bug?
is ok in release in 8.0 version?
_send_data
should be able to accept a new optional parameter: block (False by default)
.
If it's true, the function waits for the result.
I am facing a lot of issues regarding libtdjson.so in cent os 7.
OSError: /usr/lib64/libstdc++.so.6: version `GLIBCXX_3.4.22' not found (required by /home/martyn/github/ultima-code/main/scrapers/telegram/telegram_bot_barksdale/telegram/lib/linux/libtdjson.so)
This is one of the issues. can you please help me to?
Is it possible to login using bot tokens, instead of phone numbers? I see it exists in the tdlib but not in your wrapper.
First I start a shell inside the container:
docker run -i -t --rm -v /tmp/docker-:/tmp/ akhmetov/python-telegram sh
From inside the container, I then cd to the examples directory
cd /app/examples
and call get_me.py
python3 get_me.py <id> <hash> <phone>
But this error occurs:
Traceback (most recent call last):
File "get_me.py", line 17, in <module>
database_encryption_key='changeme1234',
File "/usr/local/lib/python3.6/site-packages/telegram/client.py", line 81, in __init__
library_path=library_path,
File "/usr/local/lib/python3.6/site-packages/telegram/tdjson.py", line 37, in __init__
self._build_client(library_path)
File "/usr/local/lib/python3.6/site-packages/telegram/tdjson.py", line 40, in _build_client
self._tdjson = CDLL(library_path)
File "/usr/local/lib/python3.6/ctypes/__init__.py", line 348, in __init__
self._handle = _dlopen(self._name, mode)
OSError: Error loading shared library libssl.so.1.0.0: No such file or directory (needed by /usr/local/lib/python3.6/site-packages/telegram/lib/linux/libtdjson.so)
I got this error when I'm sending a few messages in a row..
[ 0][t68][1560791165.993596792][Binlog.cpp:496][!Td] Truncate binlog "/tmp/.tdlib_files/48423ed3e97f2eea41918a3028c4454c/database/td.binlog" from size 9756 to size 9256 due to error: [Error : -2 : Event of size 5378 at offset 9256 out of 9756 [is_encrypted:true]
00001502 12100009 00000000 31736a34 5d07c87a d8ecf888 01bdf32d
]
I had to call the login() method with every message, otherwise its not working...Could this be the problem?
is python-telegram cross-platform library?
in telegram/lib i found only darwin/linux directories
Traceback (most recent call last):
File "Client.py", line 1, in <module>
from telegram.client import Telegram
File "/usr/local/lib/python3.7/dist-packages/telegram/client.py", line 12, in <module>
from telegram.utils import AsyncResult
ImportError: cannot import name 'AsyncResult' from 'telegram.utils' (/usr/local/lib/python3.7/dist-packages/telegram/utils/__init__.py)
Shouldn't be that complicated but would be nice to have.
Hello! I find it strange that I cannot find anything regarding the database_encryption_key
.
Where do I get or set that part? The rest is under control but not this part.
In Telegram's doc they say I can leave it empty. But I'm not sure if it's okay with this app.
Посмотрел пакет
постоянно растут
self._results
self._queue
и ошибка при удалении
def stop(self) -> None:
self. _tdjson._td_json_client_destroy(self.td_json_client)
Hello!
I used python-telegram library to build Telegram client. When I had launched python script in PowerShell I got pop-up window with error message. Unfortunately I didn't make a screenshot. The message said that I'm trying to launch file dedicated for another operating system and showed the path to the file contained "linux" directory.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.