Could someone help me find the error in this code? - python

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 :)

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")

Discord Bot that generates random food recipe's using Spoonacular api

I am trying to make a discord bot in Nextcord Python that will generate a random recipe using a $randomrecipe command.
I tried making it so that it would send a title of a dish (and also the image and ingredients) but I cant get it to work.
#bot.command(name='randomrecipe')
async def randomrecipe(ctx):
r = requests.get('https://api.spoonacular.com/recipes/random?apiKey=apikey')
title_name = r.json() ["title"]
await ctx.send(title_name)
here's the error for that code
Ignoring exception in command randomrecipe:
Traceback (most recent call last):
File "C:\Users\iliaa\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\ext\commands\core.py", line 168, in wrapped
ret = await coro(*args, **kwargs)
File "c:\Users\iliaa\Downloads\json\app.py", line 22, in randomrecipe
title_name = r.json() ["title"]
KeyError: 'title'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\iliaa\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\ext\commands\bot.py", line 1048, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\iliaa\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\ext\commands\core.py", line 933, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\iliaa\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\ext\commands\core.py", line 177, in wrapped
raise CommandInvokeError(exc) from exc
nextcord.ext.commands.errors.CommandInvokeError: Command raised an exception: KeyError: 'title'
This error means, that the api not returned a title.
The issue lies in following line: title_name = r.json()["title"]
Try to print put r.json() without the ["title"] print(r.json())
You will notice, that title key is not included in the response.
You are looking for title in the root element but after reproducing it, printing out the whole response, i noticed that title is located inside recipes. There are multiplie title keys and because you want the title of the dish (which is the first one) you need to index it by 0 (computers start couting at 0) so you should try to use r.json()["recipes"][0]["title"]
After using it this way, i got follwoing output:
All Day Simple Slow-Cooker FALL OFF the BONE Ribs
Here the full code i've used:
import requests
r = requests.get('https://api.spoonacular.com/recipes/random?apiKey=your_key_here')
print(r.json()["recipes"][0]["title"])

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

Ban/Kick In Discord.py error due to "permissions"

Im creating a bot that can ban and kick users if they dont follow the rules.
when i execute !ban #user it gives the error
Ignoring exception in command kick:
Traceback (most recent call last):
File "C:\Users\Daniel\AppData\Local\Programs\Python\Python37-32\lib\site-packages\discord\ext\commands\core.py", line 83, in wrapped
ret = await coro(*args, **kwargs)
File "C:/Users/Daniel/Desktop/DAN/1/8/0/1/PROGRAMMING/LegacyCoding/DiscordVidTutBot/bot.py", line 85, in kick
await ctx.guild.kick(member, reason=reason)
File "C:\Users\Daniel\AppData\Local\Programs\Python\Python37-32\lib\site-packages\discord\guild.py", line 1627, in kick
await self._state.http.kick(user.id, self.id, reason=reason)
File "C:\Users\Daniel\AppData\Local\Programs\Python\Python37-32\lib\site-packages\discord\http.py", line 221, in request
raise Forbidden(r, data)
discord.errors.Forbidden: 403 Forbidden (error code: 50013): Missing Permissions
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\Daniel\AppData\Local\Programs\Python\Python37-32\lib\site-packages\discord\ext\commands\bot.py", line 892, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\Daniel\AppData\Local\Programs\Python\Python37-32\lib\site-packages\discord\ext\commands\core.py", line 797, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\Daniel\AppData\Local\Programs\Python\Python37-32\lib\site-packages\discord\ext\commands\core.py", line 92, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: Forbidden: 403 Forbidden (error code: 50013): Missing Permissions
I have been through the developer section of discord and made sure it has all the permissions needed to execute the ban and kick command such as admin kick members ban members and still its not working. does anybody know the cause of this and how i can fix it?
I found a fix for it and it turns out that i was trying to kick a member with higher permissions than the bot had so it would not kick them.

When running bot sample code, I get this error

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 :)

Categories