How do you add more than one command/function to python.py ?
This is my code:
import os
import discord
client = discord.Client()
#client.event
async def on_ready():
print(f"{client.user} is online")
#client.event
async def on_message(message):
if message.content.startswith("https://"):
await message.delete()
client.run(my_secret)
To add more commands,
Here is the syntax for a new command
#client.command(name="wave")
async def command_name(ctx,user: discord.Member):
await ctx.send(f"{ctx.author} has waved to {user.mention}")
import discord
from discord.ext import commands
Having at least these two imports is a must. Now you should be prepared to create more commands,
as a template
#client.command()
async def command_name(arguments) :
#rest of your code here
and if the command is inside a cog
#commands.command()
async def command_name(self, other arguments) :
#rest of your code here
I suggest you to read the docs though, blindly follow won't help
Related
I am using the newest version of discord py and python. I wanted to make a custom bot with slash commands in cogs. For now my bot already has some cogs command but now slash commands thee commands work perfectly fine. I looked up some things and came up with this but as you can guess its not working. so far i wrote this code in my cog:
import discord
from discord import app_commands
from discord.ext import commands
class Slash(commands.Cog):
def __init__(self, client: commands.Bot):
self.client = client
#commands.Cog.listener()
async def on_ready(self):
print("Slash cog loaded")
#commands.command()
async def sync(self, ctx) -> None:
fmt = await ctx.client.tree.sync(guild=ctx.guild)
await ctx.send(f"Synced {len(fmt)} commands.")
#app_commands.command(name="slash", description="test slash command")
async def ping(self, interaction: discord.Interaction):
bot_latency = round(self.client.latency * 1000)
await interaction.response.send_message(f"Pong! {bot_latency} ms.")
async def setup(client):
await client.add_cog(Slash(client), guilds=[discord.Object(id="HEREISMYSERVERID")])
I also wrote this code in my main file:
import discord
from discord.ext import commands, tasks
from itertools import cycle
import os
import asyncio
import json
client = commands.Bot(command_prefix="!", intents=discord.Intents.all(), application_id=MYAPPPLICATIONID)
bot_status = cycle(["Secret Things...","cooking"])
#tasks.loop(seconds=18000)
async def change_status():
await client.change_presence(activity=discord.Game(next(bot_status)))
#client.event
async def on_ready():
print("Success: Bot is connected to Discord")
change_status.start()
async def load():
for filename in os.listdir("./cogs"):
if filename.endswith("py"):
await client.load_extension(f"cogs.{filename[:-3]}")
async def main():
async with client:
await load()
await client.start("MYTOKEN")
asyncio.run(main())```
I have also a bunch of normal cogs these work perfectly fine. also in my console i see that this slash cog was loaded. But when i try to use !sync nothing happens can someone please help me with this
The docs for add_cog say this about the guilds kwarg:
If the cog is an application command group, then this would be the guilds where the cog group would be added to. If not given then it becomes a global command instead.
Your cog is not an application command group (it's a regular cog), so this doesn't do anything. As a result, your slash command is registered as a global one. This means that syncing to the guild (sync(guild=...)) does nothing, as the command isn't registered to that guild.
You can either use app_commands.guilds to add one specific command to a guild, or create a GroupCog instead of a regular cog to do it for the entire cog.
I've just started learn python and my discord bot won't go online. it just said
" Process exit with exit code 0". And there's no error with the code.
here's my code. enter image description here
Add await client.process_commands(ctx) and #client.event don't need parentheses(). Use the code given below:
#client.event
async def on_message(ctx):
if ctx.author == client.user:
return
await client.process_commands(ctx)
Use this entire code if it still not working:
import discord
from discord.ext import commands
bot = commands.Bot(command_prefix="!")
#bot.event
async def on_ready():
print('We are logged in!')
#bot.event
async def on_message(message):
if message.author==bot.user:
return
await bot.process_commands(message)
#bot.command()
async def ping(message) :
await message.channel.send("Pong!!")
bot.run("TOKEN")
You should try this instead
import os
import discord
from discord.ext import commands
discord_token = "Your Token"
client = discord.Client()
bot = commands.Bot(command_prefix="s!")
#bot.event
async def on_ready():
print("running")
bot.run(discord_token)
#bot.command()
async def on_ready():
print("running")
bot.run(discord_token)
and the output should be running
You should try this instead
import os
import discord
from discord.ext import commands
discord_token = "Your Token"
client = discord.Client()
bot = commands.Bot(client_prefix="!")
#client.command()
async def on_ready():
print("running")
bot.run(discord_token)
The code you gave is wrong, this is correct:
import os
import discord
from discord.ext import commands
bot = commands.Bot(command_prefix="!") # you don't need an extra discord.client Bot is enough
token = os.getenv("TOKEN")
#you should not run the program here you should run it at last
#bot.event #no need for brackets
async def on_ready():
print("running")
#bot.event
async def on_message(ctx):
if ctx.author == client.user:
return
#bot.command(name="span",description="YOUR DESCRIPTION HERE") # it is command and not commands
async def span_(ctx,amount:int,*,message):
for i in range(amount):
await ctx.send(message)
bot.run(token) #you should run the bot now only and this will work perfectly!
You can find the the documentation for discord.py here.
I've been researching methods to add cooldowns to only specific commands in my bot. I am unable to find anything that works, and I'm unsure how #commands.cooldown(rate=1, per=5, bucket=commands.BucketType.user) would be implemented into this code.
import discord
import random
from pathlib import Path
from discord.ext import commands
from discord.ext.commands.cooldowns import BucketType
client = discord.Client()
#client.event
async def on_ready():
print('We have logged in as {0.user}'.format(client))
#client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('#help'):
*command goes here*
if message.content.startswith('#gamble'):
*command goes here*
client.run('TOKEN')
I suggest you using commands.Bot as it has all the functionality that discord.Client has + a full command system, your code rewrited would look like this:
import discord
from discord.ext import commands
# You should enable some intents
intents = discord.Intents.default()
bot = commands.Bot(command_prefix="#", intents=intents)
bot.remove_command("help") # Removing the default help command
#bot.event
async def on_ready():
print(f"Logged in as {bot.user}")
#bot.command()
async def help(ctx): # Commands take a `commands.Context` instance as the first argument
# ...
#bot.command()
#commands.cooldown(1, 6.0, commands.BucketType.user)
async def gamble(ctx):
# ...
bot.run("TOKEN")
Take a look at the introduction
I am dabbling in the creation of a discord bot for my private discord server and I have run into an issue.
I have three functions that load, unload and reload extensions in the form of cogs. The creation of the load and unload commands are totally fine but I am having trouble with the reload command.
In the interest of not repeating code, I want to call unload(extension) and load(extension inside of the reload(extension) command, however, I have not yet been able to figure out how to do so.
Here is my code:
import discord
from discord.ext import commands
import os
from settings import BOT_TOKEN
client = commands.Bot(command_prefix=(".", "!", "?", "-"))
#client.event
async def on_ready():
await client.change_presence(status=discord.Status.idle)
print("Discord_Bot is ready")
#client.command()
async def load(ctx, extension):
client.load_extension("cogs.{0}".format(extension))
#client.command()
async def unload(ctx, extension):
client.unload_extension("cogs.{0}".format(extension))
#client.command()
async def reload(ctx, extension):
await ctx.invoke(client.get_command("unload({0}".format(extension)))
await ctx.invoke(client.get_command("load({0})".format(extension)))
# Load Cogs on Boot
for filename in os.listdir("./cogs"):
if filename.endswith(".py"):
client.load_extension("cogs.{0}".format(filename[:-3]))
client.run(BOT_TOKEN)
I also have an example_cog.py I use to test the functionality of the load, unload and reload commands. There are no commands in this file, just the basics needed to function as a cog.
example_cog.py
import discord
from discord.ext import commands
class Example_Cog(commands.Cog):
def __init__(self, client):
self.client = client
def setup(client):
client.add_cog(Example_Cog(client))
When I use the bot on my private discord server and try to reload, it does not work. I have read the documentation and I cannot figure out how to pass arguments into the bot.get_command() function. I would vastly appreciate help on this issue.
I have tried many different ways of using the bot.get_command() function but none of them work. These include:
await ctx.invoke(client.get_command("unload {0}".format(extension)))
await ctx.invoke(client.get_command("unload({0})".format(extension)))
Thanks, Ben
You need to pass name of command in string type. Example:
#bot.event
async def on_ready():
# call command without args
await bot.get_command('examplecommand').callback()
# call command with args
await bot.get_command('exampleArgsCommand').callback(ctx, message)
#bot.command()
async def examplecommand():
pass
#bot.command()
async def exampleArgsCommand(ctx, message):
pass
im trying to make a bot for my discord server, but all my commands dont work.
im using windows and pycharm to test and use the bot. i tried many different types but nothing works. im using python 3.7
import discord
from discord.ext import commands
import asyncio
from discord.ext.commands import Bot
Client = discord.Client()
client = commands.Bot(command_prefix='.')
#client.event
async def on_ready():
print("bot is active")
#client.command()
async def ping(ctx):
await ctx.send('pong')
await print("pong")
it doesn't crash or give an error, it just doesn't do anything in the command
Try this:
import discord
from discord.ext import commands
TOKEN = YOUR_TOKEN_GOES_HERE
client = commands.Bot(command_prefix = '.')
#client.event
async def on_ready():
print("Powering up the bot")
#client.event
async def on_message(message):
print("A new message!")
await client.process_commands(message)
#client.command()
async def ping(ctx):
await ctx.channel.send("Pong!")