Эй, так что я создаю API, который интегрирован с ботом для дискордов. Однако, когда я хотел отправить сообщение на каналPython

Программы на Python
Anonymous
 Эй, так что я создаю API, который интегрирован с ботом для дискордов. Однако, когда я хотел отправить сообщение на канал

Сообщение Anonymous »

Из -за ошибки времени выполнения я попытался переключиться на использование Discord WebHooks для отправки моего сообщения, и это работает, но мне также нужно добавить реакции на сообщение через бот, но это не работает, потому что, когда я использую Discord WebHooks, он возвращается нет Данные мне, и мне нужен идентификатор сообщения, чтобы получить его и добавить реакции, то есть, если ни одна из этих функций не дает мне ошибок времени выполнения.ERROR: Exception in ASGI application
Traceback (most recent call last):
File "/home/container/.local/lib/python3.10/site-packages/uvicorn/protocols/http/h11_impl.py", line 407, in run_asgi
result = await app( # type: ignore[func-returns-value]
File "/home/container/.local/lib/python3.10/site-packages/uvicorn/middleware/proxy_headers.py", line 78, in __call__
return await self.app(scope, receive, send)
File "/home/container/.local/lib/python3.10/site-packages/fastapi/applications.py", line 271, in __call__
await super().__call__(scope, receive, send)
File "/home/container/.local/lib/python3.10/site-packages/starlette/applications.py", line 118, in __call__
await self.middleware_stack(scope, receive, send)
File "/home/container/.local/lib/python3.10/site-packages/starlette/middleware/errors.py", line 184, in __call__
raise exc
File "/home/container/.local/lib/python3.10/site-packages/starlette/middleware/errors.py", line 162, in __call__
await self.app(scope, receive, _send)
File "/home/container/.local/lib/python3.10/site-packages/starlette/middleware/exceptions.py", line 79, in __call__
raise exc
File "/home/container/.local/lib/python3.10/site-packages/starlette/middleware/exceptions.py", line 68, in __call__
await self.app(scope, receive, sender)
File "/home/container/.local/lib/python3.10/site-packages/fastapi/middleware/asyncexitstack.py", line 21, in __call__
raise e
File "/home/container/.local/lib/python3.10/site-packages/fastapi/middleware/asyncexitstack.py", line 18, in __call__
await self.app(scope, receive, send)
File "/home/container/.local/lib/python3.10/site-packages/starlette/routing.py", line 706, in __call__
await route.handle(scope, receive, send)
File "/home/container/.local/lib/python3.10/site-packages/starlette/routing.py", line 276, in handle
await self.app(scope, receive, send)
File "/home/container/.local/lib/python3.10/site-packages/starlette/routing.py", line 66, in app
response = await func(request)
File "/home/container/.local/lib/python3.10/site-packages/fastapi/routing.py", line 237, in app
raw_response = await run_endpoint_function(
File "/home/container/.local/lib/python3.10/site-packages/fastapi/routing.py", line 163, in run_endpoint_function
return await dependant.call(**values)
File "/home/container/bot.py", line 345, in test
m = await channel.send(embed=embed)
File "/home/container/.local/lib/python3.10/site-packages/discord/abc.py", line 1561, in send
data = await state.http.send_message(channel.id, params=params)
File "/home/container/.local/lib/python3.10/site-packages/discord/http.py", line 624, in request
async with self.__session.request(method, url, **kwargs) as response:
File "/home/container/.local/lib/python3.10/site-packages/aiohttp/client.py", line 1141, in __aenter__
self._resp = await self._coro
File "/home/container/.local/lib/python3.10/site-packages/aiohttp/client.py", line 467, in _request
with timer:
File "/home/container/.local/lib/python3.10/site-packages/aiohttp/helpers.py", line 701, in __enter__
raise RuntimeError(
RuntimeError: Timeout context manager should be used inside a task
< /code>
Код, который я использую для этого вызова API: < /p>
class ClanCreateBody(BaseModel):
clan_tag: str
user_id: int
username: str

@app.get("/createclan/")
async def test(body: ClanCreateBody, AuthToken: str | None = Header(default=None)):
if AuthToken == "testtoken":
pass
else:
return {"Invalid": "Token"}

check_emoji = bool(emoji.get_emoji_regexp().search(body.clan_tag))
if check_emoji:
return {"Invalid": "Emojis are not allowed in clan tags"}

if not body.clan_tag:
return {"Invalid": "There is no clan tag"}

# Check they don't already have a clan
has_clan, clan = await bot.id_has_clan_both(body.user_id)
if has_clan:
if clan.role_id == -1:
return {"Invalid": "User is already in a clan"}
else:
return {"Invalid": "User is already in a clan"}

# Check this clan name isn't already taken
name_is_taken = await bot.clan_name_is_taken(body.clan_tag)
if name_is_taken:
return {"Invalid": "This clan name is already taken!"}

# It's good to create
channel = bot.get_channel(secret_file["staff_channel_id"])
embed = discord.Embed(
title="Clan creation request",
description=f"Clan name: `{body.clan_tag}`\nRequester: {body.username}\n\n"
f"To accept this please react with a tick.\n"
f"To reject this please react with a cross.",
color=embed_color,
timestamp=discord.utils.utcnow(),
)
embed.set_footer(text=f"{body.user_id} : Sent from web")
m = await channel.send(embed=embed)
await m.add_reaction("✅")
await m.add_reaction("❎")

await bot.db.pending_clans.insert(
{
"_id": body.clan_tag.lower(),
"name": body.clan_tag,
"role_id": -1,
"clan_points": 0,
"total_koth_wins":0,
"total_roam_wins":0,
"total_maze_wins":0,
"leader_id": body.id,
"members": [],
"co_leaders": [],
"pending_invites": [],
"pending_message_id": m.id,
"created_at": datetime.datetime.now().strftime("%-I:%M %p %m/%d/%Y"),
"discord_invite": "Set with !clansetdiscord",
"video_url": "!Set with !clannew",
"channel_id": None,
}
)

for member in staff:
try:
sname = secret_file["server_name"]
await member.send(embed = discord.Embed(title= f"New Clan Application on {sname}",description=f"{body.user_id} wants to make **{body.clan_tag}** [Click Here]({m.jump_url}) to accept/decline that.",color=embed_color))

except (discord.HTTPException, discord.Forbidden):
pass

return {"Status": "Request sent"}
< /code>
Я попытался напрямую вызвать Discordapi и отправить свое сообщение прямо через это и обойти функцию discord.py, но я не мог понять это и подумал, что это все равно даст мне ту же ошибку.


Подробнее здесь: https://stackoverflow.com/questions/756 ... ver-when-i

Вернуться в «Python»