TelegramAPIError: Bad Gateway (aiogram) - python

I create a bot that notifies the user at certain times, but from time to time gives this error
dispatcher.py [LINE:390] ERROR | 2022-10-03 04:10:16,846 : Cause exception while getting updates.
Traceback (most recent call last):
File "/usr/local/lib/python3.8/dist-packages/aiogram/dispatcher/dispatcher.py", line 381, in start_polling
updates = await self.bot.get_updates(
File "/usr/local/lib/python3.8/dist-packages/aiogram/bot/bot.py", line 110, in get_updates
result = await self.request(api.Methods.GET_UPDATES, payload)
File "/usr/local/lib/python3.8/dist-packages/aiogram/bot/base.py", line 231, in request
return await api.make_request(await self.get_session(), self.server, self.__token, method, data, files,
File "/usr/local/lib/python3.8/dist-packages/aiogram/bot/api.py", line 140, in make_request
return check_result(method, response.content_type, response.status, await response.text())
File "/usr/local/lib/python3.8/dist-packages/aiogram/bot/api.py", line 128, in check_result
raise exceptions.TelegramAPIError(description)
aiogram.utils.exceptions.TelegramAPIError: Bad Gateway
I think this problem is on the telegram side itself and is solved via webhook, but I don't want to use them.

Related

What could be causing this error: RuntimeError('Event loop is closed') in Python

I am creating a discord bot in pyCharm. This is the following code I have:
# bot.py
import os
import discord
from dotenv import load_dotenv
load_dotenv()
TOKEN = os.getenv('DISCORD_TOKEN')
GUILD = os.getenv('DISCORD_GUILD')
client = discord.Client()
#client.event
async def on_ready():
for guild in client.guilds:
if guild.name == GUILD:
break
print(
f'{client.user} is connected to the following guild:\n'
f'{guild.name}(id: {guild.id})'
)
client.run(TOKEN)
When I run it the following errors are produced:
Traceback (most recent call last):
File "C:\Users\elrod\venv\lib\site-packages\discord\http.py", line 300, in static_login
data = await self.request(Route('GET', '/users/#me'))
File "C:\Users\elrod\venv\lib\site-packages\discord\http.py", line 254, 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 "C:\Users\elrod\OneDrive\Desktop\Assignments\CPSC\Python\HextchLibraryApp\HextechLibrary.py", line 25, in <module>
client.run(TOKEN)
File "C:\Users\elrod\venv\lib\site-packages\discord\client.py", line 723, in run
return future.result()
File "C:\Users\elrod\venv\lib\site-packages\discord\client.py", line 702, in runner
await self.start(*args, **kwargs)
File "C:\Users\elrod\venv\lib\site-packages\discord\client.py", line 665, in start
await self.login(*args, bot=bot)
File "C:\Users\elrod\venv\lib\site-packages\discord\client.py", line 511, in login
await self.http.static_login(token.strip(), bot=bot)
File "C:\Users\elrod\venv\lib\site-packages\discord\http.py", line 304, 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 0x0000022950CEF160>
Traceback (most recent call last):
File "C:\Users\elrod\AppData\Local\Programs\Python\Python39\lib\asyncio\proactor_events.py", line 116, in __del__
self.close()
File "C:\Users\elrod\AppData\Local\Programs\Python\Python39\lib\asyncio\proactor_events.py", line 108, in close
self._loop.call_soon(self._call_connection_lost, None)
File "C:\Users\elrod\AppData\Local\Programs\Python\Python39\lib\asyncio\base_events.py", line 751, in call_soon
self._check_closed()
File "C:\Users\elrod\AppData\Local\Programs\Python\Python39\lib\asyncio\base_events.py", line 515, in _check_closed
raise RuntimeError('Event loop is closed')
RuntimeError: Event loop is closed
Process finished with exit code 1
Now, what I find interesting is this:
I can assure you that I have a .env file set up as such:
DISCORD_TOKEN={my-token-here}
DISCORD_GUILD={my-server-here}
and it is the correct information
I know this because when I take the same token out of the .env file and just paste it directly into client.run() it works without issue, but of course this is private information!
So, the issue is that my file isnt being read properly? I would disagree because in testing I find that the string in DISCORD_GUILD is being read in properly without issue
I also tried the ole turn it off and back on trick by resetting to a new token but no luck
This is my last resort to understanding this error. Does anyone know what could be causing this error and ho to fix it?
Your .env file should look like this:
# .env
DISCORD_TOKEN = ADASIUHFOAka12312jsdfhpAFDA.GnTdIh.dOU0fjmz-WhfDebLN7x8ncuGbLVWyPXNftirGA
Should not contain the {}, if you included them (taking literally as you wrote in your question).
Also, you should set your intents under Discord Developers - Applications and declare them when defining client.

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>

RuntimeError: Event loop is closed (discord.py)

So I was making discord bot and everything seemed to be successful, until I stopped programm and started getting this error (yes... kinda big):
Traceback (most recent call last):
File "C:\Users\user\PycharmProjects\DsBots\venv\lib\site-packages\discord\http.py", line 300, in static_login
data = await self.request(Route('GET', '/users/#me'))
File "C:\Users\user\PycharmProjects\DsBots\venv\lib\site-packages\discord\http.py", line 254, 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 "C:\Users\user\PycharmProjects\DsBots\bot.py", line 30, in <module>
client.run(TOKEN)
File "C:\Users\user\PycharmProjects\DsBots\venv\lib\site-packages\discord\client.py", line 723, in run
return future.result()
File "C:\Users\user\PycharmProjects\DsBots\venv\lib\site-packages\discord\client.py", line 702, in runner
await self.start(*args, **kwargs)
File "C:\Users\user\PycharmProjects\DsBots\venv\lib\site-packages\discord\client.py", line 665, in start
await self.login(*args, bot=bot)
File "C:\Users\user\PycharmProjects\DsBots\venv\lib\site-packages\discord\client.py", line 511, in login
await self.http.static_login(token.strip(), bot=bot)
File "C:\Users\user\PycharmProjects\DsBots\venv\lib\site-packages\discord\http.py", line 304, 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 0x0000026E2673BD90>
Traceback (most recent call last):
File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\asyncio\proactor_events.py", line 116, in __del__
self.close()
File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\asyncio\proactor_events.py", line 108, in close
self._loop.call_soon(self._call_connection_lost, None)
File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\asyncio\base_events.py", line 750, in call_soon
self._check_closed()
File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\asyncio\base_events.py", line 515, in _check_closed
raise RuntimeError('Event loop is closed')
RuntimeError: Event loop is closed
So I found out that the problem is in authorization, and maybe security, or maybe an error in code causes bot to logout().
I found many same questions, but many of them was asked because of undetected syntax error.
Any suggestions?...
Edit: Sorry, forgot to post code. Here it is:
import os
import discord
from dotenv import load_dotenv
load_dotenv()
TOKEN = os.getenv("DISCORD_TOKEN")
GUILD = os.getenv("DISCORD_GUILD")
client = discord.Client()
#client.event
async def on_ready():
# print(f'{client.user} has connected to Discord!')
guild = discord.utils.get(client.guilds, name=GUILD)
print(
f'{client.user} is connected to the following guild:\n'
f'{guild.name}(id: {guild.id})\n'
)
members = '\n - '.join([member.name for member in guild.members])
print(f'Guild Members:\n - {members}')
async def on_message(message):
print(message)
client.run(TOKEN)
So the problem was because I was writting my TOKEN and GUILD in .env file in {}/"" (so it looked like DISCORD_TOKEN="token" or DISCORD_TOKEN={token}). But .env file always writes variables in string type. I didn't knew that, so I was getting LoginFailure: Improper token has been passed. (thanks to Eric Jin) because of my TOKEN and GUILD was with {}.
The problem solution was very simple:
Old code (.env file):
DISCORD_TOKEN="token"
DISCORD_GUILD="guild"
New code:
DISCORD_TOKEN=token
DISCORD_GUILD=guild
(yes...)

Embed not being sent

import discord
from discord.ext import commands
import random
import praw
cl = commands.Bot(command_prefix = '!')
reddit = praw.Reddit(client_id = "",
client_secret = "",
username = "",
password = "",
user_agent = "")
#cl.event
async def on_ready():
print("Bot is ready, get ready to do wutever u want with it")
#cl.command()
async def meme(ctx, amount=50, subr="memes", filter="top"):
all_submission = []
subreddit = reddit.subreddit("subr")
subs = subreddit.filter(limit = amount)
for submission in subs:
all_submission.append(submission)
random_sub = random.choice(all_submission)
name = random_sub.title
url = random_sub.url
em = discord.embed(title = name)
em.set_image = url
await ctx.send(embed=em)
print("embed sent")
cl.run("")
when I was running this nothing showed up but when I debugged it and !meme in discord it was showing me this traceback error thing
It appears that you are using PRAW in an asynchronous environment.
It is strongly recommended to use Async PRAW: https://asyncpraw.readthedocs.io.
Ignoring exception in command meme:
Traceback (most recent call last):
File "/home/runner/memes-bot/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "main.py", line 20, in meme
subs = subreddit.filter(limit = amount)
File "/home/runner/memes-bot/venv/lib/python3.8/site-packages/praw/models/reddit/base.py", line 34, in __getattr__
self._fetch()
File "/home/runner/memes-bot/venv/lib/python3.8/site-packages/praw/models/reddit/subreddit.py", line 584, in _fetch
data = self._fetch_data()
File "/home/runner/memes-bot/venv/lib/python3.8/site-packages/praw/models/reddit/subreddit.py", line 581, in _fetch_data
return self._reddit.request("GET", path, params)
File "/home/runner/memes-bot/venv/lib/python3.8/site-packages/praw/reddit.py", line 885, in request
return self._core.request(
File "/home/runner/memes-bot/venv/lib/python3.8/site-packages/prawcore/sessions.py", line 330, in request
return self._request_with_retries(
File "/home/runner/memes-bot/venv/lib/python3.8/site-packages/prawcore/sessions.py", line 228, in _request_with_retries
response, saved_exception = self._make_request(
File "/home/runner/memes-bot/venv/lib/python3.8/site-packages/prawcore/sessions.py", line 185, in _make_request
response = self._rate_limiter.call(
File "/home/runner/memes-bot/venv/lib/python3.8/site-packages/prawcore/rate_limit.py", line 33, in call
kwargs["headers"] = set_header_callback()
File "/home/runner/memes-bot/venv/lib/python3.8/site-packages/prawcore/sessions.py", line 283, in _set_header_callback
self._authorizer.refresh()
File "/home/runner/memes-bot/venv/lib/python3.8/site-packages/prawcore/auth.py", line 425, in refresh
self._request_token(
File "/home/runner/memes-bot/venv/lib/python3.8/site-packages/prawcore/auth.py", line 158, in _request_token
raise OAuthException(
prawcore.exceptions.OAuthException: invalid_grant error processing request
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/runner/memes-bot/venv/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "/home/runner/memes-bot/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "/home/runner/memes-bot/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: OAuthException: invalid_grant error processing request
This is the error thing I was talking about and it is very weird like telling me to download async praw which I have never had a problem with and pls help it is needed
This doesn't appear to be a discord.py issue, it appears to be related to the praw 0auth flow.
According to the traceback, there's an authentication issue in your praw credentials. Double, triple, and quadruple check your authentication credentials and flow with the workflow and methodology in the docs

It doesn’t send a message in a DM with 'discord.py'

My code:
a = 1
b = 600
#client.command()
async def iponergoopelda(ctx):
for line in range(a, b):
with open("id users2.txt") as f:
data = f.readlines()
for line in data:
user = await client.fetch_user(int(line.strip()))
await user.send('hey')
print('Отправлено')
This doesn’t a send message in a DM because the error with a DM,
Ignoring exception in command iponergoopelda:
Traceback (most recent call last):
File "C:\Users\Никитос\AppData\Local\Programs\Python\Python36\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "C:\Users\Никитос\Desktop\Nukebot.py", line 51, in iponergoopelda
await user.send('hey https://discord.com/api/oauth2/authorize?client_id=815193692432367646&permissions=2214068032&scope=bot')
File "C:\Users\Никитос\AppData\Local\Programs\Python\Python36\lib\site-packages\discord\abc.py", line 883, in send
channel = await self._get_channel()
File "C:\Users\Никитос\AppData\Local\Programs\Python\Python36\lib\site-packages\discord\user.py", line 697, in _get_channel
ch = await self.create_dm()
File "C:\Users\Никитос\AppData\Local\Programs\Python\Python36\lib\site-packages\discord\user.py", line 725, in create_dm
data = await state.http.start_private_message(self.id)
File "C:\Users\Никитос\AppData\Local\Programs\Python\Python36\lib\site-packages\discord\http.py", line 247, in request
raise HTTPException(r, data)
discord.errors.HTTPException: 400 Bad Request (error code: 50007): Cannot send messages to this user
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\Никитос\AppData\Local\Programs\Python\Python36\lib\site-packages\discord\ext\commands\bot.py", line 902, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\Никитос\AppData\Local\Programs\Python\Python36\lib\site-packages\discord\ext\commands\core.py", line 864, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\Никитос\AppData\Local\Programs\Python\Python36\lib\site-packages\discord\ext\commands\core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: HTTPException: 400 Bad Request (error code: 50007): Cannot send messages to this user
In the document I have ids for people. I tried to get it to work with three ids, but with 200 ids it doesn’t work.
How can I do it? Maybe try and except?
The user simply has the dm's disabled, and there isn't any way of sending the message then. You can put a try/except block:
a = 1
b = 600
#client.command()
async def iponergoopelda(ctx):
for line in range(a , b):
with open("id users2.txt") as f:
data = f.readlines()
for line in data:
user = await client.fetch_user(int(line.strip()))
try:
await user.send('hey')
except:
pass
print('Отправлено')

Categories

Resources