DIscord Slash Commands Interaction Failed on discord py - discord

async def _ping(ctx): # Defines a new "context" (ctx) command called "ping."
async def command_hi(ctx):
await ctx.defer()
await ctx.send("Pong!")
pass
I was making slash commands and first time it worked but secondtime, it does not work.
I tried await ctx.defer() but it's not working either

Hey #Justnoob I recommend you to use Pycord, It has inbuilt Buttons, Slash, Dropdowns and much more but for now the discord api with application commands is a bit complicated we usually use ctx.send but in app commands it is ctx.respond so here is the code:-
async def ping(ctx): #Don't use _ping too.
await ctx.respond("Pong!")
And I still don't understand why you created two async def in one command. There should be only one and you already specified it.

Related

Toggling a server limited command

#f spam
async def on_message(message):
if message.author.bot:
return
elif message.content.lower() == 'f':
await message.channel.send('f')
await bot.process_commands(message)
this is my current code for an f spam or sends an f each time a user does.
I was wanting to make this command toggleable and also server/guild limited if possible.
for example someone says !fspam and it gets toggled and switched off and when done the same again it gets turned on. OR it could be !fspam on/ !fspam off
You can use Command.enable, where you can use command.update to. This will raise the DisabledCommand error.
Also please dont just copy and paste the code, try understanding what I did.This will disable it for all the guilds to. If you want it per server then you will need to use a database.
For example:
#client.command()
async def enable(ctx,*,command):
command = client.get_command(command)
command.update(enabled=True)
await ctx.send(f"{command} enabled!")
#client.command()
async def disable(ctx,*,command):
command = client.get_command(command)
command.update(enabled=False)
await ctx.send(f"{command} disabled!")

discord.py restart the command

I am making a discord bot and I tried to make a status command that will make my bot's status start changing, so I thought its working pretty well until I realized that I need it to restart and that I have no idea how to do that, so here is my code without the restart part:
#client.command()
async def status(ctx):
await client.change_presence(activity=discord.Streaming(name='firststatus', url='https://www.twitch.tv/my-channel-name'))
await asyncio.sleep(5)
await client.change_presence(activity=discord.Activity(type=discord.ActivityType.watching, name='Secondstatus'))
so I did that but I don't know what to put at the end so it'll restart I guess it will be something like client.command.restart.
You can use a simple while loop or the built-in discord.py extension tasks
from discord.ext import tasks
#tasks.loop(seconds=5)
async def change_status():
await client.change_presence(activity=discord.Streaming(name='firststatus', url='https://www.twitch.tv/my-channel-name'))
await asyncio.sleep(5)
await client.change_presence(activity=discord.Activity(type=discord.ActivityType.watching, name='Secondstatus'))
#client.command()
async def status(ctx):
change_status.start()
The change_status function will loop every 5 seconds and change the presence. You can stop it with change_status.stop()
Reference:
tasks.loop
Loop.start
Loop.stop

how to add reaction to a specifc user?

I've been working on this piece of code:
#client.event
async def lol(message,ctx):
if ctx.author.id == <user_id>:
await message.add_reaction('❤️')
else:
return
I am pretty sure that it is developed correctly, yet I am not getting the desired results.
I am pretty sure that if you check the console, an HTTP error would have been encountered. That's because you directly pasted the emoji in the function parameter. You have to add its unicode value. In your case:
await message.add_reaction(u'\u2764')
You are using an event decorator rather than a command, unless you were trying to detect if the user reacted, but its still completely off. What it looks like, the command that is called will send a message and the bot will react to it.
#client.command()
async def lol(ctx):
message = await ctx.send(f"{ctx.author.mention}, lol")
await message.add_reaction('😂')
If you then want to detect if the user had reacted to the emoji, you can use a event, but an on_reaction_add:
#client.event
async def on_reaction_add(reaction, user):
if reaction.emoji == '😂':
await user.send("Lol")

Why can't I use my other commands after this rockpaperscissors one in discord.py?

I am writing a Discord bot but whenever I use this ,rockpaperscissors command, after the game has finished I can't use any of my other commands like ,help. Why is this?
elif message.content == ",rockpaperscissors":
await message.channel.send("```\nRock Paper Scissors\n~~~~~~~~~~~~~~~~~~~~~\nSend your move in the format ,[move] e.g. ,rock\n```")
#client.event
async def on_message(message):
_ = str(message.content).lower()[1::]
computer = random.choice(RPS)
await rockPaperScissorsChecker(message, _, computer)
return
It's not possible to tell from the code that you've given, but here are a couple possibilities of what might be causing it.
Scenario #1
You have multiple on_message events.
When using events, you don't need to write multiple ones - you can use if/elif statements to your advantage. If you do choose to have multiple, then the one that's been defined the latest in the script will be the "active" one.
Here's how to separate commands in on_message:
#client.event
async def on_message(message):
if message.author.bot:
return
elif message.content.lower().startswith(",rockpaperscissors"):
# code for the cmd here
elif message.content.lower().startswith(",cmd2"):
# second cmd code here
# etc. etc.
Scenario #2
You're using command decorators and on_message without processing the commands.
When overriding (writing your own) on_message event, you need to call Bot.process_commands() in order for the registered commands to work. Behind the scenes there's a default on_message event which has this already done, but because you're rewriting your own, you'll need to add it:
#client.event
async def on_message(message):
await client.process_commands(message)
# rest of your on_message code
References:
on_message()
Bot.process_commands() - "By default, this coroutine is called inside the on_message() event. If you choose to override the on_message() event, then you should invoke this coroutine as well."
commands.Command() - The command decorator.

Discord.py - Tag a random user

I recently started working with Discord.py.
My question is: How can I tag a random user, for example if you write !tag in the chat? I haven't found an answer yet.
if message.content.startswith('+best'):
userid = '<# # A RANDOM ID #>'
yield from client.send_message(message.channel, ' : %s is the best ' % userid)
Thank´s
Here's how I'd do it:
Generate a list of users in your server
Use random.choice to select a random user from the list
Mention that user using the API (or if you'd like, do it manually) along with your message
Here's the implementation:
from random import choice
if message.content.startswith('+best'):
user = choice(message.channel.guild.members)
yield from client.send_message(message.channel, ' : %s is the best ' % user.mention)
Elaborating on aeshthetic's answer, you can do something like this:
import random
if message.content.startswith('+best'):
channel = message.channel
randomMember = random.choice(channel.guild.members)
await channel.send(f'{randomMember.mention} is the best')
Please note that the code is in the rewrite version of discord.py and not the async version - if you're using the async version, I'd recommend you migrate to rewrite as support for the async version of discord.py has ceased. To learn more about that, refer to the migrating documentation found here.
Let me know if you need help - happy coding!
I was playing around a bit and got this to work, you can try it.
#client.command(pass_context=True)
async def hug(ctx):
user = choice(ctx.message.channel.guild.members)
await ctx.send(f'{ctx.message.author.mention} hugged {user.mention}')
First of all, I suggest you install discord.py-rewrite, as it is more advanced.
Then, I suggest you create bot commands using the #client.command() decorator, like this:
#client.command()
async def testcommand(ctx):
pass
Now that you have done both things, there are several ways to do it. For example, if you don't want the bot to mention the command invoker or other bots, you can write:
from random import choice
from discord.ext import commands
#client.command()
#commands.guild_only()
async def tag(ctx):
try:
await ctx.send(choice(tuple(member.mention for member in ctx.guild.members if not member.bot and member!=ctx.author)))
except IndexError:
await ctx.send("You are the only human member on it!")
If you don't want the bot to mention other bots, but it can mention the command invoker, use:
from random import choice
from discord.ext import commands
#client.command()
#commands.guild_only()
async def tag(ctx):
await ctx.send(choice(tuple(member.mention for member in ctx.guild.members if not member.bot)))
If you want the bot to mention any guild member, human or bot, use:
from random import choice
from discord.ext import commands
#client.command()
#commands.guild_only()
async def tag(ctx):
await ctx.send(choice(tuple(member.mention for member in ctx.guild.members)))

Resources