On discord, the module discord.ext.commands lets you create commands. I tried to create a command, with prefix="/", although it won't appear in discord's UI.
Code:
import discord
from discord.ext import commands
bot = commands.Bot(command_prefix="/")
#bot.command(name="kick", description="Kick a user to your wish.")
#commands.has_permissions(kick_members=True)
async def kick(ctx, member: discord.Member, *, reason=None):
await member.kick(reason=reason)
await ctx.send(f"The user #{member} has been kicked. Reason: {reason}.")
bot.run("mytoken")
It won't pop up.
But I want to do it like this:
You need to install discord-py-slash-command and then put the code to import it from discord-py-slash-command import SlashCommands. You can refer the code below:
import discord
from discord_slash import SlashCommand
client = discord.Client(intents=discord.Intents.all())
slash = SlashCommand(client, sync_commands=True) # Declares slash commands through the client.
guild_ids = [1234567890] # Put your server IDs in this array.
#slash.slash(name="ping", guild_ids=guild_ids)
async def _ping(ctx):
await ctx.send("Pong!")
client.run("token")
Related
I have a little problem which you can skip and does not give you a big error that doesn't let you run the bot, by it is very frustrating tho.
Code:
import asyncio
import discord
from discord.ext import commands
from main import db
^^^^ Unable to import 'main' [pylint(import-error)]
import datetime
import random
I am using cogs so that's why I am importing from main.
If you are using cogs you don't have to import main. Just give a look to the discord.py docs and you will see that cogs must be like this:
import discord
from discord.ext import commands
class MembersCog(commands.Cog):
def __init__(self, bot):
self.bot = bot
#commands.command()
#commands.guild_only()
async def joined(self, ctx, *, member: discord.Member):
"""Says when a member joined."""
await ctx.send(f'{member.display_name} joined on {member.joined_at}')
#commands.command(name='coolbot')
async def cool_bot(self, ctx):
"""Is the bot cool?"""
await ctx.send('This bot is cool. :)')
#commands.command(name='top_role', aliases=['toprole'])
#commands.guild_only()
async def show_toprole(self, ctx, *, member: discord.Member=None):
"""Simple command which shows the members Top Role."""
if member is None:
member = ctx.author
await ctx.send(f'The top role for {member.display_name} is {member.top_role.name}')
def setup(bot):
bot.add_cog(MembersCog(bot))
And in main.py: bot.load_extension('folder_name.file_name')
This is just an example.
i've encountered an issue where I can't seem to get my addrole command to work. I've searched through every video and article and have spent hours to try and figure out why my code isn't working.
I want it so whenever a admin calls the ,addrole command, the user they mentioned gets that role.
(example: ,addrole #{rolename} {#user}).
Here is 2 sections of the code which I think may be the issue.
Here is the imports and some other things.
from discord.ext import commands
import random
from discord import Intents
import os
from discord import Embed
from discord.ext.commands import has_permissions
from discord.utils import get
from dotenv import load_dotenv
load_dotenv()
TOKEN = os.getenv("TOKEN")
intents = discord.Intents.default()
intents.members = True
client = commands.Bot(command_prefix=",", intents=intents)
Here is the command.
#commands.has_permissions(administrator=True)
async def addrole(ctx, role: discord.Role, user: discord.Member):
await user.add_roles(role)
await ctx.send(f"{user.mention} has successfully received the role {role.mention}.")
I've tried changing so many things but whenever I run it and call the command nothing happens.
Thanks.
Your command is not responding as it is missing client.command() which actually calls the command
#client.command()
#commands.has_permissions(administrator=True)
async def addrole(ctx, role: discord.Role, user: discord.Member):
await user.add_roles(role)
await ctx.send(f"{user.mention} has successfully received the role {role.mention}.")
It may also be better if your allow the role to have multiple arguments, which means you can add a role to a user with spaces, for example, This role instead of Thisrole, this can be added by adding * which creates an multiple string argument. You would then need to pass it as the last argument.
#client.command()
#commands.has_permissions(administrator=True)
async def addrole(ctx, user: discord.Member=None, *, role: discord.Role):
if user == None:
await ctx.send('Please format like ,addrole #member role')
return
await user.add_roles(role)
await ctx.send(f"{user.mention} has successfully received the role {role.mention}.")
I still have not figured out how to add/remove roles on the bot itself, without executing commands in the chat. It has to be silently in the background. Can someone please help me.
Current code below that does work but not the way I want it to. I do not want the bot to type a command to give itself a role, I need it to automatically give it silently without any chat messages being executed. My ideal idea is to execute the addRole function in the on_ready event somehow, without sending message to get a role.
import aiohttp
from datetime import datetime
from dotenv import load_dotenv
from discord.ext import commands
import discord
import os
load_dotenv()
DISCORD_TOKEN = os.getenv("DISCORD_TOKEN")
bot = commands.Bot(command_prefix="$")
bot.remove_command('help')
#bot.event
async def on_ready():
await bot.wait_until_ready()
bot.session = aiohttp.ClientSession()
await bot.get_channel(402353715718277809).send("$addRole")
#bot.command()
async def addRole(ctx):
role = discord.utils.get(ctx.guild.roles, name="market_green")
member = ctx.guild.get_member(bot.user.id)
await member.add_roles(role)
bot.run(DISCORD_TOKEN)
The guild object in discord.py has a .me attribute (docs) which represents yourself in that guild.
So on start you can get that guild based on it's id (in the on_ready event) and assign yourself a role with add_roles, example code(with guildid the id of the guild you want the role in):
guild = bot.get_guild(guildid)
role = discord.utils.get(guild.roles, name="market_green")
await guild.me.add_roles(role)
can someone tell my why my code is not working?
i want the bot to message me what i type after !test.
import discord
from discord.ext.commands import Bot
from discord.ext import commands
from discord import Game
command_prefix = "!"
client = discord.Client()
bot = commands.Bot(command_prefix='!')
#client.event
async def on_ready():
print('prihlaseno za {0.user}'.format(client))
#bot.command()
async def test(ctx, *, mess):
await ctx.send(mess)
client.run('token')
You cannot mix client with bot. Use one or the other (bot is typically used). Then change your code to fit one of these. For example, if you pick bot, rename #client.event to bot.event and change client.run to bot.run.
You are also needlessly importing the Bot class again when you have already imported it from discord.ext.commands. I'm also not sure what discord.Game is at the end of your imports.
role specific command yes its working finally got it.
from discord.ext import commands
bot = commands.Bot('?')
#bot.command(pass_context=True)
#commands.has_any_role("Admin", "Moderator")
async def hello(ctx):
await bot.say("Hello {}".format(ctx.message.author.mention))
You can use the discord.ext.commands extension, which offers a has_any_role decorator.
from discord.ext import commands
bot = commands.Bot('?')
#bot.command(pass_context=True)
#commands.has_any_role("Admin", "Moderator")
async def hello(ctx):
await bot.say("Hello {}".format(ctx.message.author.mention))