python telethon ConnectionError: Connection to Telegram failed 5 time(s) - python

I'm trying to get every new message sent in a channel with python and then use the data to do some further processing. This is my code:
api_id = *******
api_hash = '**********************'
client = TelegramClient(
'session_name',
api_id,
api_hash,
)
client.start()
print(client.get_me().stringify())
client.send_message('someone', 'Hello! Talking to you from Telethon')
And this is the error that I get:
C:\Users\erfan\AppData\Local\Programs\Python\Python39\python.exe "C:/Users/erfan/Desktop/Boors py/main.py"
Traceback (most recent call last):
File "C:\Users\erfan\Desktop\Boors py\main.py", line 14, in <module>
client.start()
File "C:\Users\erfan\AppData\Local\Programs\Python\Python39\lib\site-packages\telethon\client\auth.py", line 133, in start
else self.loop.run_until_complete(coro)
File "C:\Users\erfan\AppData\Local\Programs\Python\Python39\lib\asyncio\base_events.py", line 642, in run_until_complete
return future.result()
File "C:\Users\erfan\AppData\Local\Programs\Python\Python39\lib\site-packages\telethon\client\auth.py", line 140, in _start
await self.connect()
File "C:\Users\erfan\AppData\Local\Programs\Python\Python39\lib\site-packages\telethon\client\telegrambaseclient.py", line 516, in connect
if not await self._sender.connect(self._connection(
File "C:\Users\erfan\AppData\Local\Programs\Python\Python39\lib\site-packages\telethon\network\mtprotosender.py", line 123, in connect
await self._connect()
File "C:\Users\erfan\AppData\Local\Programs\Python\Python39\lib\site-packages\telethon\network\mtprotosender.py", line 249, in _connect
raise ConnectionError('Connection to Telegram failed {} time(s)'.format(self._retries))
ConnectionError: Connection to Telegram failed 5 time(s)
Process finished with exit code 1
Telegram is blocked by my country. So I use Lantern to have access to it and I can access web.telegram.com. I also tried using a mtproxy but got the same error.

I don't know which part of my code was wrong, but as I saw many people had the same problem, I decided to post my solution.
I could get telethon work very well with help of this article.
And as I said telegram is blocked in my country so I could use MTProxy with help of telethon documentation at this part: 2.2.5 Using MTProto Proxies.

Related

Trying to get AIOKafka to work with self-signed cert (Python)

I've been banging my head against my keyboard for a day now, so I'm giving up and asking for help.
I've got a working consumer using confluence kafka, but I need to make it run as a coroutine so I can get things working with FastAPI. I really wanted to try out AIOKafka for this, but for the life of me, I can't get it to work with a self-signed certificate (this is in our dev env).
Here is the working config for my confluence kafka consumer:
conf = {
"bootstrap.servers": "10.142.252.214:9093",
"group.id": "myConsumerID",
"security.protocol": "SASL_SSL",
"sasl.username": kafkaUser,
"sasl.password": kafkaPass,
"sasl.mechanisms": "PLAIN",
"enable.ssl.certificate.verification": "False",
"on_commit": commit_completed,
"heartbeat.interval.ms": "1000",
"socket.connection.setup.timeout.ms": "10000",
"auto.offset.reset": "earliest"
}
Here is the code I'm trying to use for AIOKafka
async def consume():
cert = "../foo/cert/certificate.pem"
key = "../foo/cert/key.pem"
context2 = ssl.create_default_context()
context2.load_cert_chain(certfile=cert, keyfile=key)
context2.check_hostname = False
context2.verify_mode = CERT_NONE
#context2.ssl_cafile="../foo/cert/CARoot.pem"
context2.ssl_certfile = "cert.pem"
context2.ssl_keyfile = "key.pem"
context2.ssl_password = kafkaKey
context2.ssl_keystore_type = "PEM"
consumer = AIOKafkaConsumer(
'TopicA', 'TopicB',
bootstrap_servers="10.142.252.214:9093",
group_id="myConsumerGroup",
sasl_plain_username="kafkaUser",
sasl_plain_password="kafkaPass",
sasl_mechanism="PLAIN",
security_protocol="SASL_SSL",
ssl_context=context2)
await consumer.start()
try:
# Consume messages
async for msg in consumer:
print("consumed: ", msg.topic, msg.partition, msg.offset,
msg.key, msg.value, msg.timestamp)
finally:
# Will leave consumer group; perform autocommit if enabled.
await consumer.stop()
When I try to run this, I just get the most cryptic errors ever and I can't make any sense on where to start trying to figure out what's wrong.
$ python test-main.py
Traceback (most recent call last):
File "/Users/myUser/.pyenv/versions/3.10.5/lib/python3.10/site-packages/aiokafka/conn.py", line 375, in _on_read_task_error
read_task.result()
File "/Users/myUser/.pyenv/versions/3.10.5/lib/python3.10/site-packages/aiokafka/conn.py", line 518, in _read
resp = await reader.readexactly(4)
File "/Users/myUser/.pyenv/versions/3.10.5/lib/python3.10/asyncio/streams.py", line 706, in readexactly
raise exceptions.IncompleteReadError(incomplete, n)
asyncio.exceptions.IncompleteReadError: 0 bytes read on a total of 4 expected bytes
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/Users/myUser/scripts/ansible-hello-world/test-main.py", line 165, in <module>
asyncio.run(consume())
File "/Users/myUser/.pyenv/versions/3.10.5/lib/python3.10/asyncio/runners.py", line 44, in run
return loop.run_until_complete(main)
File "/Users/myUser/.pyenv/versions/3.10.5/lib/python3.10/asyncio/base_events.py", line 646, in run_until_complete
return future.result()
File "/Users/myUser/scripts/ansible-hello-world/test-main.py", line 155, in consume
await consumer.start()
File "/Users/myUser/.pyenv/versions/3.10.5/lib/python3.10/site-packages/aiokafka/consumer/consumer.py", line 346, in start
await self._client.bootstrap()
File "/Users/myUser/.pyenv/versions/3.10.5/lib/python3.10/site-packages/aiokafka/client.py", line 210, in bootstrap
bootstrap_conn = await create_conn(
File "/Users/myUser/.pyenv/versions/3.10.5/lib/python3.10/site-packages/aiokafka/conn.py", line 96, in create_conn
await conn.connect()
File "/Users/myUser/.pyenv/versions/3.10.5/lib/python3.10/site-packages/aiokafka/conn.py", line 234, in connect
await self._do_sasl_handshake()
File "/Users/myUser/.pyenv/versions/3.10.5/lib/python3.10/site-packages/aiokafka/conn.py", line 314, in _do_sasl_handshake
auth_bytes = await self._send_sasl_token(
File "/Users/myUser/.pyenv/versions/3.10.5/lib/python3.10/asyncio/tasks.py", line 445, in wait_for
return fut.result()
kafka.errors.KafkaConnectionError: KafkaConnectionError: Connection at 10.142.252.214:9093 closed
Unclosed AIOKafkaConsumer
consumer: <aiokafka.consumer.consumer.AIOKafkaConsumer object at 0x107338670>

Telethon doesn't work with channel ID but works with username

Hi i want ot try to receive a notification every time a channel send new messages, for this i have created this snippet:
from telethon import TelegramClient, events
api_id = XXXX
api_hash = 'XXXXXXX'
channelId = '-100XXXXXXXX'
client = TelegramClient('anon', api_id, api_hash)
client.start()
#client.on(events.NewMessage(chats = [channelId]))
async def main(event):
# print(event.raw_text)
client.run_until_disconnected()
But i don't understand why work only if use username in channelID, i want use ID because some channel are private.
I used the bot "#username_to_id_bot" in telegram to retrieve the ID through the link of channel.
When use username work fine but when i use the ID o channel return this error:
Task exception was never retrieved
future: <Task finished name='Task-10' coro=<UpdateMethods._dispatch_update() done, defined at C:\Users\Administrator\AppData\Local\Programs\Python\Python310\lib\site-packages\telethon\client\updates.py:399> exception=ValueError('Cannot find any entity corresponding to "-100XXXXXXXX"')>
Traceback (most recent call last):
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python310\lib\site-packages\telethon\client\updates.py", line 458, in _dispatch_update
await builder.resolve(self)
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python310\lib\site-packages\telethon\events\common.py", line 99, in resolve
await self._resolve(client)
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python310\lib\site-packages\telethon\events\newmessage.py", line 93, in _resolve
await super()._resolve(client)
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python310\lib\site-packages\telethon\events\common.py", line 103, in _resolve
self.chats = await _into_id_set(client, self.chats)
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python310\lib\site-packages\telethon\events\common.py", line 33, in _into_id_set
chat = await client.get_input_entity(chat)
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python310\lib\site-packages\telethon\client\users.py", line 437, in get_input_entity
await self._get_entity_from_string(peer))
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python310\lib\site-packages\telethon\client\users.py", line 574, in _get_entity_from_string
raise ValueError(
ValueError: Cannot find any entity corresponding to "-100xxxxx"
I have tried to pass also entities like this example without success:
https://ingrom.com/python/47397/telethon-get-channel-id
can someone help me to find a solution ?
Here
#client.on(events.NewMessage(chats = [channelId]))
you should use entity instead of chats, like
#client.on(events.NewMessage(entity = channelId, message = "message you need to send"))

RuntimeError: Event loop is closed when connecting python discord bot

I just started writing a discord bot with python and although the code is very simple, I somehow keep getting a RuntimeError when trying to connect
I checked the token multiple times
would really appreciate it if someone could tell me what I did wrong
python Script:
import discord
from discord.ext import commands
bot = commands.Bot(command_prefix=':')
#bot.event
async def on_ready():
print('bot is ready')
bot.run('my_token')
here is the traceback:
Traceback (most recent call last):
File "C:\Users\orang\Projects\PythonProjects\discord_lyrics_bot\venv\lib\site-packages\discord\http.py", line 293, in static_login
data = await self.request(Route('GET', '/users/#me'))
File "C:\Users\orang\Projects\PythonProjects\discord_lyrics_bot\venv\lib\site-packages\discord\http.py", line 247, in request
raise HTTPException(r, data)
discord.errors.HTTPException: 401 Unauthorized (error code: 0): 401: Unauthorized
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File ".\main.py", line 12, in <module>
bot.run('Bxb-8dRGeYHYLFD5-IXGhNfY1TnX3kKA')
File "C:\Users\orang\Projects\PythonProjects\discord_lyrics_bot\venv\lib\site-packages\discord\client.py", line 718, in run
return future.result()
File "C:\Users\orang\Projects\PythonProjects\discord_lyrics_bot\venv\lib\site-packages\discord\client.py", line 697, in runner
await self.start(*args, **kwargs)
File "C:\Users\orang\Projects\PythonProjects\discord_lyrics_bot\venv\lib\site-packages\discord\client.py", line 660, in start
await self.login(*args, bot=bot)
File "C:\Users\orang\Projects\PythonProjects\discord_lyrics_bot\venv\lib\site-packages\discord\client.py", line 509, in login
await self.http.static_login(token.strip(), bot=bot)
File "C:\Users\orang\Projects\PythonProjects\discord_lyrics_bot\venv\lib\site-packages\discord\http.py", line 297, in static_login
raise LoginFailure('Improper token has been passed.') from exc
discord.errors.LoginFailure: Improper token has been passed.
Exception ignored in: <function _ProactorBasePipeTransport.__del__ at 0x00000217D658C670>
Traceback (most recent call last):
File "C:\Users\orang\AppData\Local\Programs\Python\Python38\lib\asyncio\proactor_events.py", line 116, in __del__
self.close()
File "C:\Users\orang\AppData\Local\Programs\Python\Python38\lib\asyncio\proactor_events.py", line 108, in close
self._loop.call_soon(self._call_connection_lost, None)
File "C:\Users\orang\AppData\Local\Programs\Python\Python38\lib\asyncio\base_events.py", line 719, in call_soon
self._check_closed()
File "C:\Users\orang\AppData\Local\Programs\Python\Python38\lib\asyncio\base_events.py", line 508, in _check_closed
raise RuntimeError('Event loop is closed')
RuntimeError: Event loop is closed
You're using the wrong discord token. First of all, you leaked your bot token
bot.run('Bxb-8dRGeYHYLFD5-IXGhNfY1TnX3kKA')
Regenerate your toek ASAP. Second, make sure you grab the token in the Bot Tab, and you don't get any of the other tokens. I can tell that the token is too short and is the wrong token.
I'm pretty sure you're using the client secret code, which is not your bot's token. What you have to do is go to applications in Discord's Developer Portal. Once you're there, click on your bot application, and then go to the Bot tab on the left (it will have a little puzzle piece next to it). Over there, you should see Click to Reveal Token under Build-A-Bot. You can either click that and copy what shows up, or you can simply click the Copy button which will automatically copy the bot's token for you. Please do not share your token with anyone, as it can be used to run other people's code if they have access to it. If you've already leaked it, just go ahead and click the Regenerate button, which will give you a new token for your bot, and it will null the older token so that nobody can use your bot anymore.

Running telethon on pythonanywhere

try to run a basic scripts that adds members to a telegram group over pythoneverywhere server. I installed the main package which is telethon in the server. but i am getting the error in the image below. what am i not doing right?
error message is given below
21:02 ~/Villians TV/Villians5/TeleGram-Scraper-master $ python3 villians5.py
Traceback (most recent call last):
File "villians5.py", line 17, in <module>
client.connect()
File "/home/somti13/.local/lib/python3.8/site-packages/telethon/sync.py", line 39, in syncified
return loop.run_until_complete(coro)
File "/usr/lib/python3.8/asyncio/base_events.py", line 608, in run_until_complete
return future.result()
File "/home/somti13/.local/lib/python3.8/site-packages/telethon/client/telegrambaseclient.py", line 472, in connect
if not await self._sender.connect(self._connection(
File "/home/somti13/.local/lib/python3.8/site-packages/telethon/network/mtprotosender.py", line 125, in connect
await self._connect()
File "/home/somti13/.local/lib/python3.8/site-packages/telethon/network/mtprotosender.py", line 250, in _connect
raise ConnectionError('Connection to Telegram failed {} time(s)'.format(self._retries))
ConnectionError: Connection to Telegram failed 5 time(s)
The mtproto connection type for telegram does not work for free accounts on PythonAnywhere. Only http(s) connections out of PythonAnywhere will work for free accounts.

Cannot connect bot to Bale messenger API: network connection disconnected

I was trying my first bot in bale messenger but I couldn't and faced this error. Is there any one here to help me?
2018-05-05 11:13:47,938 network.py:112 WARNING:"network connection disconnected."
2018-05-05 11:13:47,939 network.py:36 ERROR:"connect error: 500, message='Invalid response status'"
Traceback (most recent call last):
File "/home/ehsan/PycharmProjects/example_bots/venv/lib/python3.5/site-packages/balebot/connection/network.py", line 31, in connect self._ws = await self._session.ws_connect(self.construct_url())
File "/home/ehsan/PycharmProjects/example_bots/venv/lib/python3.5/site-packages/aiohttp/helpers.py", line 109, in __await__ ret = yield from self._coro
File "/home/ehsan/PycharmProjects/example_bots/venv/lib/python3.5/site-packages/aiohttp/client.py", line 465, in _ws_connect
headers=resp.headers) aiohttp.client_exceptions.WSServerHandshakeError: 500, message='Invalid response status'
it seems you use a websocket to connect your bot to server. and its a handshake error now. make sure the Token you have given from botfather was correct. If there is no problem with that it may be with your server address.

Categories

Resources