When running bot sample code, I get this error - python

My code is exactly
This
(With my token of course)
When I run it, my bot starts up as normal, but when a new person is added to the server, i get this.
------
Ignoring exception in on_member_join
Traceback (most recent call last):
File "C:\Users\USRNAME\AppData\Local\Programs\Python\Python36\lib\site-packages\discord\client.py", line 307, in _run_event
yield from getattr(self, event)(*args, **kwargs)
File "test.py", line 9, in on_member_join
await client.send_message(server, fmt.format(member, server))
File "C:\Users\USRNAME\AppData\Local\Programs\Python\Python36\lib\site-packages\discord\client.py", line 1152, in send_message
data = yield from self.http.send_message(channel_id, content, guild_id=guild_id, tts=tts, embed=embed)
File "C:\Users\USRNAME\AppData\Local\Programs\Python\Python36\lib\site-packages\discord\http.py", line 198, in request
raise NotFound(r, data)
discord.errors.NotFound: NOT FOUND (status code: 404): Unknown Channel
(Sorry about it not being in a code block, I'm new to stack exchange)
Any help would be appreciated. Thanks

This will not work anymore because discord removed default channels so sending it to server will not work. You should replace server with discord.Object('insert channel id') if you are using async or discord.Object(insert channel id) if you are using the rewrite branch. Note the string vs int difference. Good luck :)

Related

Edit a button more than once on a Discord bot using Nextcord

So, I'm using Nextcord to make a Discord bot. I have some buttons that I would like to edit the style more than once.
At first, I tried with interaction.response.edit_message(), which works great once but the second time, it gives me this error:
nextcord.errors.InteractionResponded: This interaction has already been responded to before
I learned that I can't use interaction.response more than once, so I knew I had to get creative here. I got suggested to use the interaction.edit() or interaction.message.edit().
interaction.message.edit() gives me that error even if I do it only once:
Ignoring exception in view <ChoicesView timeout=180.0 children=9> for item <ChoicesBtn style=<ButtonStyle.success: 3> url=None disabled=False label='Party' emoji=None row=0>:
Traceback (most recent call last):
File "/home/runner/Raids-Master-buttons-labels/venv/lib/python3.8/site-packages/nextcord/ui/view.py", line 371, in _scheduled_task
await item.callback(interaction)
File "main.py", line 45, in callback
await interaction.message.edit(view=self.view)
File "/home/runner/Raids-Master-buttons-labels/venv/lib/python3.8/site-packages/nextcord/message.py", line 1367, in edit
data = await self._state.http.edit_message(self.channel.id, self.id, **payload)
File "/home/runner/Raids-Master-buttons-labels/venv/lib/python3.8/site-packages/nextcord/http.py", line 333, in request
raise NotFound(response, data)
nextcord.errors.NotFound: 404 Not Found (error code: 10008): Unknown Message
If I use interaction.edit(), it works once but I get a very similar error if I do it twice.
Ignoring exception in view <ChoicesView timeout=180.0 children=9> for item <ChoicesBtn style=<ButtonStyle.secondary: 2> url=None disabled=False label='Birth' emoji=None row=2>:
Traceback (most recent call last):
File "/home/runner/Raids-Master-buttons-labels/venv/lib/python3.8/site-packages/nextcord/ui/view.py", line 371, in _scheduled_task
await item.callback(interaction)
File "main.py", line 46, in callback
await interaction.edit(view=self.view)
File "/home/runner/Raids-Master-buttons-labels/venv/lib/python3.8/site-packages/nextcord/interactions.py", line 551, in edit
return await self.message.edit(*args, **kwargs)
File "/home/runner/Raids-Master-buttons-labels/venv/lib/python3.8/site-packages/nextcord/message.py", line 1367, in edit
data = await self._state.http.edit_message(self.channel.id, self.id, **payload)
File "/home/runner/Raids-Master-buttons-labels/venv/lib/python3.8/site-packages/nextcord/http.py", line 333, in request
raise NotFound(response, data)
nextcord.errors.NotFound: 404 Not Found (error code: 10008): Unknown Message
I tried to manually change the state of interaction.response._responded attribute to False but then I got this error
Ignoring exception in view <ChoicesView timeout=180.0 children=9> for item <ChoicesBtn style=<ButtonStyle.success: 3> url=None disabled=False label='Party' emoji=None row=0>:
Traceback (most recent call last):
File "/home/runner/Raids-Master-buttons-labels/venv/lib/python3.8/site-packages/nextcord/ui/view.py", line 371, in _scheduled_task
await item.callback(interaction)
File "main.py", line 47, in callback
await interaction.edit(view=self.view)
File "/home/runner/Raids-Master-buttons-labels/venv/lib/python3.8/site-packages/nextcord/interactions.py", line 549, in edit
return await self.response.edit_message(*args, **kwargs)
File "/home/runner/Raids-Master-buttons-labels/venv/lib/python3.8/site-packages/nextcord/interactions.py", line 959, in edit_message
await adapter.create_interaction_response(
File "/home/runner/Raids-Master-buttons-labels/venv/lib/python3.8/site-packages/nextcord/webhook/async_.py", line 191, in request
raise HTTPException(response, data)
nextcord.errors.HTTPException: 400 Bad Request (error code: 40060): Interaction has already been acknowledged.
I don't know what to try after that, I tried to read the interaction definition on GitHub but I admit that it's too much for me... I didn't share the code but all I'm doing is redefining the callback method on a custom class based on nextcord.ui.Button
I know it's a lot but I tried to give you as much information as possible. Thanks for taking the time and let me know if I wasn't clear enough on some things !!
When you pass the button argument into the code you can use the button.style attribute to change the button style. You can also use button.label to change what the text is on the label.
Example which turns green and says Hi! when you click it:
import nextcord
from nextcord.ext import commands
# Define a simple View that gives us a counter button
class HelloButtons(nextcord.ui.View):
#nextcord.ui.button(label="Press me!", style=nextcord.ButtonStyle.red)
async def sayhi(self, button: nextcord.ui.Button, interaction: nextcord.Interaction):
button.style = nextcord.ButtonStyle.green
button.label="Thanks for pressing me!"
await interaction.response.edit_message(view=self)
bot = commands.Bot()
#bot.slash_command()
async def counter(interaction):
await interaction.send("Press the button!", view=HelloButtons())
bot.run("token")

I get a HTTP Exception 405 error when I run my py-cord program

I am trying to create a discord bot with slash commands for the first time and I keep on getting this error when I run my program!
Ignoring exception in on_connect
Traceback (most recent call last):
File "/home/runner/AgonizingDrabEmbeds/venv/lib/python3.8/site-packages/discord/client.py", line 352, in _run_event
await coro(*args, **kwargs)
File "/home/runner/AgonizingDrabEmbeds/venv/lib/python3.8/site-packages/discord/bot.py", line 793, in on_connect
await self.register_commands()
File "/home/runner/AgonizingDrabEmbeds/venv/lib/python3.8/site-packages/discord/bot.py", line 460, in register_commands
await self.http.bulk_upsert_command_permissions(
File "/home/runner/AgonizingDrabEmbeds/venv/lib/python3.8/site-packages/discord/http.py", line 338, in request
raise HTTPException(response, data)
discord.errors.HTTPException: 405 Method Not Allowed (error code: 0): 405: Method Not Allowed
Bot is online!
this is my code:
import discord
import os
token = os.environ["nekto"]
client = discord.Bot(owner_id=<my_user_id>)
async def on_ready():
print('Bot is online!')
guilds_ids = [<myGuildId>]
client.add_listener(on_ready)
client.run(token)
Help would be appreciated
I was hitting the same issue. As per the comments suggested, I went and checked their Github.
Found the ticket. If I understand it correctly, there used to be an issue, but that has been resolved long time ago. So if you're running an old version, then you can try to update.
For me, 2.0.0.b1 still had the bug, 2.0.0rc1 had fixed the issue.
If you're running a newer version, a dirty venv is the probably cause. Delete the venv folder and build it again.

Could someone help me find the error in this code?

Here is my code:
from discord.ext import commands
import os
import discord
import requests
import json
my_secret = os.environ['MY_TOKEN']
GUILD = os.getenv('DISCORD_GUILD')
bot = commands.Bot(command_prefix='!') #prefix
discord.CustomActivity("Jaxon\'s brain melt", ActivityType="watching", emoji=None)
#bot.command(name="enfr", help="Translates text from english to french")
async def enfr(ctx, text):
response = requests.get("https://api.mymemory.translated.net/get?q=" + text + "&langpair=en|fr")
json_data = json.loads(response.text)
translation = json_data.get("translatedText") + "test"
print(response.status_code)
await ctx.channel.send(translation)
bot.run(my_secret)
This is the error I get:
200
Ignoring exception in command enfr:
Traceback (most recent call last):
File "/home/runner/translate-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 22, in enfr
await ctx.channel.send(translation)
File "/home/runner/translate-Bot/venv/lib/python3.8/site-packages/discord/abc.py", line 1065, in send
data = await state.http.send_message(channel.id, content, tts=tts, embed=embed,
File "/home/runner/translate-Bot/venv/lib/python3.8/site-packages/discord/http.py", line 254, in request
raise HTTPException(r, data)
discord.errors.HTTPException: 400 Bad Request (error code: 50006): Cannot send an empty message
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/runner/translate-Bot/venv/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "/home/runner/translate-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/translate-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: HTTPException: 400 Bad Request (error code: 50006): Cannot send an empty message
It worked a few days ago and now it doesn't :(
There is one other command, but it doesn't don't affect this one so I removed it from the code to clear it up a bit. I get that error when I try to run the command !enfr hello
I don't know if this is the correct place to ask, my last questions were disliked by some people.
The traceback specifies the error is Cannot send an empty message. Specifically:
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: HTTPException: 400 Bad Request (error code: 50006): Cannot send an empty message
Looking at it more closely you can find the line of your file where the Exception is being thrown.
File "main.py", line 22, in enfr await ctx.channel.send(translation)
From these it seems quite clear that translation is None or an empty string, and that the function ctx.channel.send throws an Exception when that is the case.
Now try to figure out why translation is empty by reviewing how you're creating it in the first place, and account for these edge-cases.
Note: Reading traceback logs might seem daunting at first, but they're quite informative (at worst showing you where in your code the issue is). Don't panic and just go through them slowly :)

Nextcord Slash Command | nextcord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body

I was migrating my bot from discord.py to nextcord and I changed my help command to a slash command, but it kept showing me this error:
nextcord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
It said that the error was caused by exceeding 2000 characters in the web.
Full Error:
Ignoring exception in on_connect
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/nextcord/client.py", line 415, in _run_event
await coro(*args, **kwargs)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/nextcord/client.py", line 1894, in on_connect
await self.rollout_application_commands()
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/nextcord/client.py", line 1931, in rollout_application_commands
await self.register_new_application_commands(data=global_payload)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/nextcord/client.py", line 1855, in register_new_application_commands
await self._connection.register_new_application_commands(data=data, guild_id=None)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/nextcord/state.py", line 736, in register_new_application_commands
await self.register_application_command(app_cmd, guild_id)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/nextcord/state.py", line 754, in register_application_command
raw_response = await self.http.upsert_global_command(self.application_id, payload)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/nextcord/http.py", line 337, in request
raise HTTPException(response, data)
nextcord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
Code
#client.slash_command(name="help",description="Help Command!")
async def help(ctx: nextcord.Interaction, *, command: str = nextcord.SlashOption(name="Command",description="The command you want to get help on.")):
embedh = nextcord.Embed(title="Help",description="Help Menu is here!",color=nextcord.Color.green())
embedh.set_footer(text=f'Requested by {ctx.author}',icon_url=ctx.author.avatar.url)
embedh.add_field(name="General", value="`dm` `say` `poll`")
embedh.add_field(name="Fun",value="`avatar` `giveaway` `8ball`",inline=False)
embedh.add_field(name="Events",value="`guessthenumber`", inline=False)
embedh.add_field(name="Image",value="`wanted`")
embedh.add_field(name="Moderation",value="`ban` `unban` `kick` `mute` `warn` `purge` `wakeup` `makerole` `slowmode` `role` `lock` `unlock` `nickname`",inline=False)
embedh.add_field(name="Utility", value="`ping` `help` `prefix` `setprefix` `serverinfo` `feedback` `credits` `support` `website` `guild`")
await ctx.response.send(embed=embedh)
Information
JSON Error Code (I got it from here): 50035
IDE: Replit
Module: nextcord
How do I resolve this error?
Explanation
From the discord dev docs:
CHAT_INPUT command names and command option names must match the following regex ^[\w-]{1,32}$
The regex essentially translates to:
If there is a lowercase variant of any letters used, you must use those
In this case, your option name, 'Command' has an uppercase 'C', which is disallowed.
Note: The length of the name must also be lower or equal to 32.
Reference
Application command naming

My telegram userbot can forward a message in private but not in a supergroup

I am writing a small project related to userbots in telegram. I had a problem when trying to forward a message from a supergroup to another user, but when I try to forward messages from a regular chat, everything is successful. I found a similar question, but unfortunately bots are used there, not userbots.
Lib: pyrogram
Version: 1.4.8
my code:
#app.on_message(filters.group & filters.text)
async def formessage(client, message):
text = message.text.lower()
# other code
await message.forward(botdata["id"])
I also tried using the function: app.forward_messages(botdata["id"], message.chat.id, message.message_id)
but alas, I get the same error
The error that I get when a new message in the supergroup:
Traceback (most recent call last):
File "C:\Users\nyansterowo\AppData\Local\Programs\Python\Python310\lib\site-packages\pyrogram\methods\advanced\resolve_peer.py", line 121, in resolve_peer
return await self.storage.get_peer_by_id(peer_id)
File "C:\Users\nyansterowo\AppData\Local\Programs\Python\Python310\lib\site-packages\pyrogram\storage\sqlite_storage.py", line 147, in get_peer_by_id
raise KeyError(f"ID not found: {peer_id}")
KeyError: 'ID not found: 5279709634'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\nyansterowo\AppData\Local\Programs\Python\Python310\lib\site-packages\pyrogram\dispatcher.py", line 222, in handler_worker
await handler.callback(self.client, *args)
File "C:\Users\nyansterowo\Desktop\tg\src\UserBot.py", line 43, in formessage
await message.forward(botdata["id"])
File "C:\Users\nyansterowo\AppData\Local\Programs\Python\Python310\lib\site-packages\pyrogram\types\messages_and_media\message.py", line 2924, in forward
return await self._client.forward_messages(
File "C:\Users\nyansterowo\AppData\Local\Programs\Python\Python310\lib\site-packages\pyrogram\methods\messages\forward_messages.py", line 83, in forward_messages
to_peer=await self.resolve_peer(chat_id),
File "C:\Users\nyansterowo\AppData\Local\Programs\Python\Python310\lib\site-packages\pyrogram\methods\advanced\resolve_peer.py", line 123, in resolve_peer
raise PeerIdInvalid
pyrogram.errors.exceptions.bad_request_400.PeerIdInvalid: Telegram says: [400 PEER_ID_INVALID] - The peer id being used is invalid or not known yet. Make sure you meet the peer before interacting with it
Let me remind you once again that I am writing a selfie and not a bot. I can easily forward a message from the group to someone through the telegram client itself, but I can’t do it through the code.
Firstly, the error you get is clear. The Session of your userbot has not yet met the group and cannot identify it based on its ID. You will have to receive any kind of update from that entity first.
See this FAQ entry: https://docs.pyrogram.org/faq/peer-id-invalid-error
Secondly, the group you are trying to forward from may have forwards restricted in its group settings. Since you can forward via an official client, this is likely not the case.

Categories