Running telethon on pythonanywhere - python

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.

Related

Python/Pyrogram on Mac Server Suddenly Turning up Error 61 Connection Refused

I have a Pyrogram app that has been running for ages with no problems from a server running MacOS. A few days ago, the code suddenly hung up and refuses to work. As soon as I attempt to start the Pyrogram Client(), I immediately get "Err 61 Connection Refused"/"network issues" errors. I have confirmed that my Telegram API account is totally fine. The next assumption was that it was an IP ban issue, but I can't even get the Client to open a socket to an http proxy. Pyrogram documentation has nothing about an Error 61, and now I'm thinking that the problem isn't with Pyrogram but rather with a core Python library (corrupted?).
I have seen references on Stackoverflow to folks running into analogous problems with other Python api/web applications but not randomly after a year of normal operation. Some of them were able to resolve the issue by switching references to "localhost" to "127.0.0.1", but I have no idea where that would be located within the Pyrogram library, nor why that would suddenly be a problem out of the blue with no code or server changes.
Help! ;) Thanks!!
Update:
I forgot to post code:
import os
import logging
from typing import List, Tuple, Optional
import re
import math
from datetime import datetime
import os.path
import asyncio
import pyrogram
import yaml
import time
import base64
import sys
import mysql.connector
import subprocess
client = pyrogram.Client(
"media_downloader",
api_id,
api_hash,
)
... and there it ends.
INFO:pyrogram.connection.connection:Connecting...
WARNING:pyrogram.connection.connection:Unable to connect due to network issues: [Errno 61] Connection refused
INFO:pyrogram.connection.connection:Connecting...
WARNING:pyrogram.connection.connection:Unable to connect due to network issues: [Errno 61] Connection refused
INFO:pyrogram.connection.connection:Connecting...
^CTraceback (most recent call last):
File "/Users/admin/home/telegram/get_message_media_v2.py", line 99, in <module>
with client:
File "/usr/local/lib/python3.9/site-packages/pyrogram/client.py", line 251, in __enter__
return self.start()
File "/usr/local/lib/python3.9/site-packages/pyrogram/sync.py", line 66, in async_to_sync_wrap
return loop.run_until_complete(coroutine)
File "/usr/local/Cellar/python#3.9/3.9.4/Frameworks/Python.framework/Versions/3.9/lib/python3.9/asyncio/base_events.py", line 629, in run_until_complete
self.run_forever()
File "/usr/local/Cellar/python#3.9/3.9.4/Frameworks/Python.framework/Versions/3.9/lib/python3.9/asyncio/base_events.py", line 596, in run_forever
self._run_once()
File "/usr/local/Cellar/python#3.9/3.9.4/Frameworks/Python.framework/Versions/3.9/lib/python3.9/asyncio/base_events.py", line 1854, in _run_once
event_list = self._selector.select(timeout)
File "/usr/local/Cellar/python#3.9/3.9.4/Frameworks/Python.framework/Versions/3.9/lib/python3.9/selectors.py", line 562, in select
kev_list = self._selector.control(None, max_ev, timeout)
KeyboardInterrupt
After attempting with a proxy:
INFO:pyrogram.connection.transport.tcp.tcp:Using proxy [PROXY REDACTED]
INFO:pyrogram.connection.connection:Connecting...
WARNING:pyrogram.connection.connection:Unable to connect due to network issues: Socket error: timed out
INFO:pyrogram.connection.transport.tcp.tcp:Using proxy [PROXY REDACTED]
INFO:pyrogram.connection.connection:Connecting...
^X^CTraceback (most recent call last):
File "/Users/admin/home/telegram/get_message_media_v2.py", line 106, in <module>
with client:
File "/usr/local/lib/python3.9/site-packages/pyrogram/client.py", line 251, in __enter__
return self.start()
File "/usr/local/lib/python3.9/site-packages/pyrogram/sync.py", line 66, in async_to_sync_wrap
return loop.run_until_complete(coroutine)
File "/usr/local/Cellar/python#3.9/3.9.4/Frameworks/Python.framework/Versions/3.9/lib/python3.9/asyncio/base_events.py", line 629, in run_until_complete
self.run_forever()
File "/usr/local/Cellar/python#3.9/3.9.4/Frameworks/Python.framework/Versions/3.9/lib/python3.9/asyncio/base_events.py", line 596, in run_forever
self._run_once()
File "/usr/local/Cellar/python#3.9/3.9.4/Frameworks/Python.framework/Versions/3.9/lib/python3.9/asyncio/base_events.py", line 1890, in _run_once
handle._run()
File "/usr/local/Cellar/python#3.9/3.9.4/Frameworks/Python.framework/Versions/3.9/lib/python3.9/asyncio/events.py", line 80, in _run
self._context.run(self._callback, *self._args)
File "/usr/local/lib/python3.9/site-packages/pyrogram/methods/utilities/start.py", line 52, in start
is_authorized = await self.connect()
File "/usr/local/lib/python3.9/site-packages/pyrogram/methods/auth/connect.py", line 46, in connect
await self.session.start()
File "/usr/local/lib/python3.9/site-packages/pyrogram/session/session.py", line 105, in start
await self.connection.connect()
File "/usr/local/lib/python3.9/site-packages/pyrogram/connection/connection.py", line 57, in connect
await self.protocol.connect(self.address)
File "/usr/local/lib/python3.9/site-packages/pyrogram/connection/transport/tcp/tcp_abridged_o.py", line 40, in connect
await super().connect(address)
File "/usr/local/lib/python3.9/site-packages/pyrogram/connection/transport/tcp/tcp.py", line 82, in connect
self.socket.connect(address)
File "/usr/local/lib/python3.9/site-packages/socks.py", line 47, in wrapper
return function(*args, **kwargs)
File "/usr/local/lib/python3.9/site-packages/socks.py", line 809, in connect
negotiate(self, dest_addr, dest_port)
File "/usr/local/lib/python3.9/site-packages/socks.py", line 443, in _negotiate_SOCKS5
self.proxy_peername, self.proxy_sockname = self._SOCKS5_request(
File "/usr/local/lib/python3.9/site-packages/socks.py", line 470, in _SOCKS5_request
chosen_auth = self._readall(reader, 2)
File "/usr/local/lib/python3.9/site-packages/socks.py", line 276, in _readall
d = file.read(count - len(data))
File "/usr/local/Cellar/python#3.9/3.9.4/Frameworks/Python.framework/Versions/3.9/lib/python3.9/socket.py", line 704, in readinto
return self._sock.recv_into(b)
KeyboardInterrupt
If anyone else runs into this problem, I was able to eventually resolve this by using pip3 to reinstall/upgrade Pyrogram. I still don't know the exact underlying cause, and at this point, I can only assume that either my copy of Pyrogram got corrupted somehow, or else there were changes to Telegram that broke a slightly older version of Pyrogram (I had 1.7.1 installed previously and pip upgraded it to 2.0.35).
pip3 install pyrogram --upgrade

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>

python connecting to ble device with passkey using bleak

I'm trying to connect to a ble device with bleak that uses a passkey.
async def connect(self, address):
print("Connecting to device...")
async with BleakClient(address) as client:
response = await client.connect()
print(response)
i'm using above code. The device displays the passkey to enter and windows displays the add a device message to input the code, but i get a timeout error from asyncio and never recieve the response to python.
Traceback (most recent call last):
File "C:\Users\halmelam\PycharmProjects\read_passcode\main.py", line 137, in <module>
asyncio.run(pair.connect(device.address))
File "C:\Users\halmelam\AppData\Local\Programs\Python\Python39\lib\asyncio\runners.py", line 44, in run
return loop.run_until_complete(main)
File "C:\Users\halmelam\AppData\Local\Programs\Python\Python39\lib\asyncio\base_events.py", line 642, in run_until_complete
return future.result()
File "C:\Users\halmelam\PycharmProjects\read_passcode\main.py", line 95, in connect
response = await client.connect()
File "C:\Users\halmelam\.virtualenvs\read_passcode\lib\site-packages\bleak\backends\winrt\client.py", line 249, in connect
await asyncio.wait_for(event.wait(), timeout=timeout)
File "C:\Users\halmelam\AppData\Local\Programs\Python\Python39\lib\asyncio\tasks.py", line 494, in wait_for
raise exceptions.TimeoutError() from exc
asyncio.exceptions.TimeoutError
How do I get the response and how can i send the passkey via python?

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

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.

Django Redis Error unknown command 'BZPOPMIN'

I've installed Redis 3.0.54.
Django is updated.
I'm learning channels from the tutorial page.
This is my terminal window for redis-cli and redis server
Image of Terminal
System check identified no issues (0 silenced).
August 06, 2020 - 16:04:58
Django version 3.1, using settings 'mysite.settings'
Starting ASGI/Channels version 2.4.0 development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
HTTP GET /chat/lobby/ 200 [0.02, 127.0.0.1:60841]
WebSocket HANDSHAKING /ws/chat/lobby/ [127.0.0.1:60843]
WebSocket CONNECT /ws/chat/lobby/ [127.0.0.1:60843]
Exception inside application: ERR unknown command 'BZPOPMIN'
Traceback (most recent call last):
File "C:\Users\\Envs\py2\lib\site-packages\channels\sessions.py", line 183, in __call__
return await self.inner(receive, self.send)
File "C:\Users\\Envs\py2\lib\site-packages\channels\middleware.py", line 41, in coroutine_call
await inner_instance(receive, send)
File "C:\Users\\Envs\py2\lib\site-packages\channels\consumer.py", line 59, in __call__
[receive, self.channel_receive], self.dispatch
File "C:\Users\\Envs\py2\lib\site-packages\channels\utils.py", line 58, in await_many_dispatch
await task
File "C:\Users\\Envs\py2\lib\site-packages\channels\utils.py", line 50, in await_many_dispatch
result = task.result()
File "C:\Users\\Envs\py2\lib\site-packages\channels_redis\core.py", line 453, in receive
real_channel
File "C:\Users\\Envs\py2\lib\site-packages\channels_redis\core.py", line 508, in receive_single
index, channel_key, timeout=self.brpop_timeout
File "C:\Users\\Envs\py2\lib\site-packages\channels_redis\core.py", line 345, in _brpop_with_clean
result = await connection.bzpopmin(channel, timeout=timeout)
aioredis.errors.ReplyError: ERR unknown command 'BZPOPMIN'
WebSocket DISCONNECT /ws/chat/lobby/ [127.0.0.1:60843]
BZPOPMIN and BZPOPMAX(also non-blocking versions ZPOPMIN and ZPOPMAX) are "Available since 5.0.0". You need to upgrade your redis to at least version 5 to use them, since you use version 3.0.54.
You may check download page for available versions and instructions to download them.
download the latest version of Redis from here and try it will work
https://github.com/tporadowski/redis/releases

Categories

Resources