I have a problem in my code.
this is my admin code :
import discord
class Admin(discord.Cog):
def __init__(self, bot):
self.bot = bot
self._last_member = None
#discord.command(name='clear', description='Permet de purger les messages du chat textuel.')
async def clear(self, ctx:discord.ApplicationContext, amount):
await ctx.channel.purge(limit=int(amount))
if __name__ == "__main__":
import main
this is my main code :
# Import discord libs
import discord
from discord.ext import commands
# Import addon libs
import random
import asyncio
# Import extra libs
from libs import settings
# Import Cogs
import admin
client = commands.Bot(command_prefix=" ", help_command=None, intents=discord.Intents.default())
client.add_cog(admin.Admin(client))
#client.event
async def on_ready():
print(f"logged in as {client.user}")
print("Bot is ready!")
await client.change_presence(status=discord.Status.online)
async def changepresence():
await client.wait_until_ready()
statuses = settings.BotStatus
while not client.is_closed():
status = random.choice(statuses)
await client.change_presence(activity=discord.Game(name=status))
await asyncio.sleep(10)
client.loop.create_task(changepresence())
client.run(settings.TOKEN)
this is my console in Visual studio code :
when i use my command /clear amount: he result this error :
but the command /clear amount: working perfectly :D
Can you help me to fix this please :D ?
You need to have the bot respond to the interaction: interaction.response.send_message("message")
Related
Complete newbie here, I'm trying to make a discord bot but, I have a problem where it says "The command help is already an existing command or alias." whenever I run it.
import discord, random
from random import randint
from discord.ext import commands
TOKEN = ""
intents=discord.Intents.all()
bot = commands.Bot(command_prefix='?', intents=intents)
#bot.event
async def on_ready() :
print(f'{bot.user} has connected to Discord !!')
#bot.command()
async def help(ctx) :
await ctx.send('commands:')
await ctx.send('1. Random - Random number')
await ctx.send('2. Ping - say "Hello"')
#bot.command()
async def random(ctx) :
await ctx.send(randint(1, 100))
enter code here
bot.run(TOKEN)
As mentioned in the comments help is a default command, but you can disable it
with
help_command=None in your commands.Bot function
import discord, random
from random import randint
from discord.ext import commands
TOKEN = ""
intents=discord.Intents.all()
bot = commands.Bot(command_prefix='?', intents=intents,help_command=None)
#bot.event
async def on_ready() :
print(f'{bot.user} has connected to Discord !!')
#bot.command(name='help')
async def my_help(ctx) :
await ctx.send('commands:')
await ctx.send('1. Random - Random number')
await ctx.send('2. Ping - say "Hello"')
#bot.command(name='random')
async def my_random(ctx) :
await ctx.send(randint(1, 100))
enter code here
bot.run(TOKEN)
Problem : nextcord.ext.commands.errors.CommandNotFound: Command
"roles" is not found
cog.py file:
from nextcord.ext import commands
from button_roles.role_view import RoleView
class ButtonRoles(commands.Cog, name="Board Roles"):
def __init__(self, bot: commands.Bot):
self.bot = bot
#commands.Cog.listener()
async def on_ready(self):
self.bot.add_view(RoleView())
#commands.command()
#commands.is_owner()
async def roles(self, ctx: commands.Context):
await ctx.send("Click a button to add or remove a role.", view=RoleView())
def setup(bot: commands.Bot):
bot.add_cog(ButtonRoles(bot))
role_view.py file:
import nextcord
from bot import custom_id
import config
VIEW_NAME = "RoleView"
class RoleView(nextcord.ui.View):
def __init__(self):
super().__init__(timeout=None)
#nextcord.ui.button(label="NSFW", emoji=":dart:", style=nextcord.ButtonStyle.primary, custom_id=custom_id(VIEW_NAME, config.NSFW_ROLE_ID))
async def nsfw_button(self, button, interaction):
interaction.response.send_message("Ты получил NSFW роль")
bot.py file
from code import interact
from unicodedata import name
from nextcord.ext import commands
import config
import os
import nextcord
import textwrap
import requests, json, random, datetime, asyncio
from PIL import Image, ImageFont, ImageDraw
from nextcord import File, ButtonStyle, Interaction, ChannelType, SlashOption
from nextcord.ui import Button, View
from nextcord.abc import GuildChannel
from dotenv import load_dotenv
load_dotenv()
intents = nextcord.Intents.default()
intents.members = True
bot = commands.Bot(command_prefix=config.PREFIX, intents=intents)
serverID = config.GUILD_ID
BOT_NAME = config.BOT_NAME
#bot.event
async def on_ready():
print(f"Logged in as {bot.user} (ID: {bot.user.id})")
#bot.slash_command(name="add", guild_ids = [serverID])
async def add(ctx, left: int, right: int):
"""Слаживать левое и правое число"""
await ctx.send(left + right)
#bot.slash_command(name="splx", guild_ids = [serverID])
async def _bot(ctx):
"""Вся инфа"""
await ctx.send("Читается как Суплекс а не спликс")
def custom_id(view: str, id: int) -> str:
return f"{config.BOT_NAME}:{view}:{id}"
if __name__ == '__main__':
bot.run(os.getenv("DISCORD_TOKEN"))
Bot successfully running without problems, and others commands running also without mistakes, however instead of $roles one
I need to know how to make a bot able to react to a trigger $roles, thanks (i'm new in discord bots developing so sorry bcs of my stupism)
well, the commands was indented incorrectly in the cog file.
you should make the commands defined in the cog file in the cog defination, like this:
class ABC(commands.Cog):
...
# like this, the commands defination should be cog defination indent level+1
#commands.command()
...
# NOT like this
#commands.command()
...
I'm trying to create a music bot for discord and I finish the code and tried to run it and when I run the play command it simply says this.
Ignoring exception in command None:
discord.ext.commands.errors.CommandNotFound: Command "play" is not found
Here's my code.
import discord
from discord.ext import commands
import youtube_dl
TOKEN = "Token here"
bot = discord.ext.commands.Bot(command_prefix = "s ");
#bot.event
async def on_ready():
channel = discord.utils.get(bot.get_all_channels(), id=794444804607574026)
await channel.connect()
async def play(ctx, url):
player = await voice_client.create_ytdl_player(url)
player.start()
bot.run(TOKEN)
You haven't added #bot.command(name="play") above the play function
import discord
from discord.ext import commands
import youtube_dl
TOKEN = "Token here"
bot = discord.ext.commands.Bot(command_prefix = "s ");
#bot.event
async def on_ready():
channel = discord.utils.get(bot.get_all_channels(), id=794444804607574026)
await channel.connect()
#bot.command(name="play")
async def play(ctx, url):
player = await voice_client.create_ytdl_player(url)
player.start()
bot.run(TOKEN)
before
async def play(ctx, url):
player = await voice_client.create_ytdl_player(url)
player.start()
after
#bot.command()
async def play(ctx, url):
player = await voice_client.create_ytdl_player(url)
player.start()
Simply use this code:
main.py
from discord.ext import commands
from discord.ext.commands import bot
import discord
import os
import youtube_dl
bot = commands.Bot(command_prefix="s")
#bot.event
async def on_ready()
print("{0.user} is online".format(bot))
#bot.command()
async def play(ctx, url):
player = await voice_client.create_ytdl_player(url)
player.start()
.env
TOKEN=<paste your token here>
Hope it’s helped you (:
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 am currently trying to create my discord bot. sadly, this does not work and I have no Idea why...
import discord
import os
import time
from ka import keep_alive
from discord.ext import commands
import asyncio
client = commands.Bot(command_prefix = '.')
prefix = '.'
#client.event
async def on_ready():
print("I'm ready! {0.user}".format(client))
await client.change_presence(activity=discord.Activity(type=discord.ActivityType.watching, name="Croissants!"))
#client.command()
async def join(ctx):
channel = ctx.message.author.voice.voice_channel
await client.join_voice_channel(channel)
await ctx.send("On my way!")
client.run(os.getenv('TOKEN'))
there are NO errors. But no output aswell. I try making it join my vc by writing: .join
channel returns None, because ctx.message.author don't have voice attribute. Also, Client.join_voice_channel is deprecated since v1.0 (read here)
Instead of that, try this:
import discord
import os
import time
from ka import keep_alive
from discord.ext import commands
import asyncio
client = commands.Bot(command_prefix = '.')
prefix = '.'
#client.event
async def on_ready():
print("I'm ready! {0.user}".format(client))
await client.change_presence(activity=discord.Activity(type=discord.ActivityType.watching, name="Croissants!"))
#client.command()
async def join(ctx):
channel = ctx.guild.get_member(ctx.author.id).voice.channel # This
await channel.connect()
await ctx.send("On my way!")
client.run(os.getenv('TOKEN'))
Do client.add_command(join). You currently have the function for your command, but you haven't told the bot to recognize it as a command.