What is the difference between #client.command and #commands.command - python

import discord
from discord.ext import commands
client = commands.Bot(command_prefix = "", intents = discord.Intents.all())
class music(commands.Cog):
def __init__(self, client):
self.client = client
#client.command()
async def join(self, ctx):
if ctx.author.voice is None:
await ctx.send("You are not in a voice channel")
Both #client.command() and #commands.command() works, what does the differences actually ?
import discord
from discord.ext import commands
client = commands.Bot(command_prefix = "", intents = discord.Intents.all())
class music(commands.Cog):
def __init__(self, client):
self.client = client
#commands.command()
async def join(self, ctx):
if ctx.author.voice is None:
await ctx.send("You are not in a voice channel")

Using #client/bot.commands() is when you are using a file that isn't being called in a cog or another folder.
#commands.command() is when client/bot isn't defined also making it so in your async def parameter have to call client
Example:
#client.command()
async def hi(ctx):
await ctx.send("Hey!")
Or for cogs:
#commands.command()
async def hi(client,ctx):
await ctx.send("Hey")

#client.command() is a command that can only be used in the main file (where client is defined)
#commands.command() is can be used in both cogs and the main file. This is way cleaner than a huge 3k lines long main file

#commands.command is used to create a command while #client.command is to create and register one. #commands.command() is usually used in a cog, since the cog will register them when loaded.
#client.command() shouldn't be used in cogs. Since it's a shortcut for:
#commands.command()
client.add_command
it will be added twice (by the shortcut and the cog), and cause an error.

Related

How to make a Discord slash command usuable in DMs

I want to use a slash command in DMs. Take this simple test.py file in the folder cogs/.
import discord
from discord.ext import commands
from discord import app_commands
class Test(commands.Cog):
def __init__(self, bot: commands.Bot) -> None:
self.bot = bot
#commands.Cog.listener()
async def on_ready(self):
print("Loaded test command cog.")
#app_commands.command(name="test", description="Test command")
async def test(self, interaction: discord.Interaction):
await interaction.response.send_message(f'Hello')
async def setup(bot: commands.Bot) -> None:
await bot.add_cog(Test(bot))
Outside the cogs folder is my launch_bot.py file which start the bot:
import discord
from discord.ext import commands
import json
with open("cogs/jsons/settings.json") as json_file:
data_dict = json.load(json_file)
guild_id = data_dict["guild_id"]
class MyBot(commands.Bot):
def __init__(self) -> None:
super().__init__(
command_prefix = "kt$",
intents = discord.Intents.all(),
tree_cls=CustomCommandTree)
async def setup_hook(self) -> None:
for filename in os.listdir("./cogs"):
if filename.endswith(".py"):
await self.load_extension(f"cogs.{filename[:-3]}")
await bot.tree.sync(guild=discord.Object(id=guild_id))
async def on_ready(self):
application_info = await self.application_info()
bot_owner = application_info.owner
await bot_owner.create_dm()
self.bot_owner_dm_channel = bot_owner.dm_channel
await self.change_presence(activity=discord.Game(presence_message))
print(f"Logged in as\n\tName: {self.user.name}\n\tID: {self.user.id}")
print(f"Running pycord version: {discord.__version__}")
print(f"Synced commands to guild with id {guild_id}.")
bot = MyBot()
bot.run(bot_token)
I tried following the instructions which were described in link but I have no guild specified, so this doesn't work.
The docs says it should work but it doesn't for me any ideas?
If you are using pycord, at least for me commands were usable in dm's by default. I'll show you how to disable that if you ever need to.
#bot.command()
#commands.guild_only()
async def example(ctx):
#do things

Discord.py bot won't leave a voice chat

i'm currently using these commands to make my bot leave/join a vc. Joining works fine, but leaving won't work.
import discord
from discord.ext import commands
import youtube_dl
class music(commands.Cog):
def __init__(self, client):
self.client = client
#commands.command()
async def join(self,ctx):
if ctx.author.voice is None:
await ctx.send("You're not in a voice channel!")
voice_channel = ctx.author.voice.channel
if ctx.voice_client is None:
await voice_channel.connect()
else:
await ctx.voice_channel.move_to(voice_channel)
#commands.command()
async def disconnect(self,ctx):
await ctx.voice_client.disconnect()
Any help in understanding why would be really appreciated!
try with:
#commands.command()
async def disconnect(self,arg):
await arg.voice_client.disconnect(force=True)
and also replace channel name from ctx to arg cause it takes ctx as current channel (its not possible to type in voice channel afaik)

Discord Bot Joining Message is not working python

Hello i try a lot commands to fix it but the bot is doing nothing
Here is my Code. The File are bot.py
import discord
import os
from discord.ext import commands
class MyClient(discord.Client):
async def on_ready(self):
print('Logged on as {0}!'.format(self.user))
async def on_message(self, message):
print('Message from {0.author}: {0.content}'.format(message))
client = MyClient()
#client.event
async def on_ready():
print(f'{client.user.name} Test!')
###############
bot = commands.Bot(command_prefix="!")
#bot.event
async def on_guild_join(guild):
if guild.system_channel:
await guild.system_channel.send("Test")
##client.event
#async def on_member_join(member):
# await ctx.author.send("Welcome!")
##*#client.event
#async def on_member_join(member):
# await member.create_dm()
# await member.send(
# f'Hallo{member.name}, Willkommen'
# )
Why is it not working i try a lot Commands/models whatever.
I use Notepad++ to programming. Give it a better Programm to programming with Python? Maybe what for Beginners?
You cant use both discord.Client and commands.Bot, choose one of them.
commands.Bot is basically the same as discord.Client but with the extra commands feature
-> Docs
# so first remove the client part in your code
# and define the Bot | you can name it 'bot' or 'client'
# bot = commands.Bot(command_prefix="!")
# is the same as
# client = commands.Bot(command_prefix="!")
# also make sure to enable Intents
intents = discord.Intents.default()
intents.member = True
bot = commands.Bot(command_prefix="!", intents=intents)
#now you can add events
#bot.event
async def on_guild_join(guild):
if guild.system_channel:
await guild.system_channel.send("Test")
#bot.event
async def on_member_join(member):
await member.send("welcome!")
# and commands
#bot.command()
async def slap(ctx, member: discord.Member):
await ctx.send(f"{ctx.author} gave {member} a slap")
# at the very end run your bot
bot.run('BOT TOKEN')

Discord greetings with cogs ,on_member_join , doen't work

My on_member_join listener doesn't execute properly. The idea is that when a new person enters my discord, my bot greets them with a custom message.
There are no syntax errors and the class loads correctly. The on_ready listener responds correctly with Welcome: ON. If I try to do a debug print it is not executed.
Where am I doing wrong? I don't understand, it seems correct to me.
import discord
from discord.ext import commands
intents = discord.Intents.default()
intents.members = True
client = discord.Client(intents=intents)
class Welcome(commands.Cog):
def __init__(self,client):
self.client=client
#commands.Cog.listener()
async def on_ready(self):
print("Welcome: ON")
#commands.Cog.listener()
async def on_member_join(self, member):
guild= client.get_guild(828676048039706694)
channel=guild.get_channel(828676048039706697)
if channel is not None:
await channel.send(f'Welcome {member.mention}.')
#commands.command()
async def Modulo_benvenuto(self,ctx):
await ctx.send('')
def setup(client):
client.add_cog(Welcome(client))
This is my main file:
import discord
import os
from discord.ext import commands
client = commands.Bot(command_prefix = '.')
#client.command()
async def load(ctx, extension):
client.load_extension(f'cogs.{extension}')
#client.command()
async def unload(ctx, extension):
client.unload_extension(f'cogs.{extension}')
#client.command()
async def reload(ctx, extension):
client.unload_extension(f'cogs.{extension}')
client.load_extension(f'cogs.{extension}')
for filename in os.listdir('./cogs'):
if filename.endswith('.py'):
client.load_extension(f'cogs.{filename[:-3]}')
client.run('TOKEN')
With a new bot it works, this is the code:
import discord
from discord.ext import commands
intents = discord.Intents.default()
intents.members = True
client = discord.Client(intents=intents)
#client.event
async def on_ready():
print("Bot is on")
#client.event
async def on_member_join(member):
print(member)
await member.send("hello")
guild = client.get_guild(831588406089744435)
channel = discord.utils.get(member.guild.channels, id=831588406089744438)
if guild:
print("guild ok")
else:
print("guild not found")
if channel is not None:
await channel.send(f'Welcome to the {guild.name} Discord Server, {member.mention} ! :partying_face:')
else:
print("id channel wrong")
client.run('TOKEN')
For the on_member_join() event reference, you need the Server Members Intent privileged gateway intent to be on. This has to be done both in your bot's page as well as in your script (which you already have done):
Go to the Discord Developer Portal.
Select the application and, under settings, navigate to Bot.
If you scroll down just a bit, you'll reach a section title Privileged Gateway Intents and, under that, SERVER MEMBERS INTENT.
Toggle the SERVERS MEMBERS INTENT to ON.
In the image below, it would be the second of the privileged gateway intents.
The issue with your code is likely because you have a discord.Bot instance defined in both your cog file as well as your main file. Since setup(client) is defined in your cog file and client.load_extension() is called in your main file, you should delete the following lines from your cog file:
cog.py
intents = discord.Intents.default()
intents.members = True
client = discord.Client(intents=intents)
However, to conserve the Intents, you'll want to add the following lines before your discord.Bot() call:
main.py
from discord.ext import commands
intents = discord.Intents.default()
intents.members = True
client = commands.Bot(command_prefix=".", intents=intents)
For your code, I would recommend using the Client.fetch_channel method, since it eliminates the possibility that an incorrect Guild ID results in channel being None.
async def on_member_join(self, member):
channel = await client.fetch_channel(1234567890)
if channel is not None:
await channel.send(f"Welcome {member.mention}.")
Or, you could just use discord.utils.get() and member.guild.channels:
async def on_member_join(self, member):
channel = discord.utils.get(member.guild.channels, id=1234567890)
if channel is not None:
await channel.send(f"Welcome {member.mention}.")
Just a suggestion for reducing potential bugs.
HOW TO FIX :
MAIN FILE
import discord
import os
from discord.ext import commands
intents = discord.Intents.default()
client = commands.Bot(command_prefix = '.', intents=intents)
intents.members = True
#client.command()
async def load(ctx, extension):
client.load_extension(f'cogs.{extension}')
#client.command()
async def unload(ctx, extension):
client.unload_extension(f'cogs.{extension}')
#client.command()
async def reload(ctx, extension):
client.unload_extension(f'cogs.{extension}')
client.load_extension(f'cogs.{extension}')
for filename in os.listdir('./cogs'):
if filename.endswith('.py'):
client.load_extension(f'cogs.{filename[:-3]}')
client.run('TOKEN')
COG FILE
import discord
from discord.ext import commands
class Welcome(commands.Cog):
def __init__(self, client):
self.client=client
#commands.Cog.listener()
async def on_ready(self):
print("Welcome: ON")
#commands.Cog.listener()
async def on_member_join(self, member):
print(member)
await member.send("hello")
guild = self.client.get_guild(831588406089744435)
channel = discord.utils.get(member.guild.channels, id=831588406089744438)
if guild:
print("guild ok")
else:
print("guild not found")
if channel is not None:
await channel.send(f'Welcome to the {guild.name} Discord Server, {member.mention} ! :partying_face:')
else:
print("id channel wrong")
#commands.command()
async def Modulo_benvenuto(self, ctx):
await ctx.send('test')
def setup(client):
client.add_cog(Welcome(client))

How do I use Client in a cog in discord.py?

I'm trying to give my bot a status inside my 'on_ready.py' cog. So when it comes online the status switches to idle and a command prefix shows in the 'playing' part of the bot's profile.
This is my current code:
#commands.Cog.listener()
async def on_ready(self):
print('Bot is online.')
and I'm trying to implement this:
#commands.Cog.listener()
async def on_ready(self):
await client.change presence(status=discord.Status.idle, activity=discord.Game('f.'))
print('Bot is online.')
I'm new to this so any help is appreciated.
edit: this is the code for the full cog:
import discord
from discord.ext import commands
class OnReady(commands.Cog):
def __init__(self, client):
self.client = client
#commands.Cog.listener()
async def on_ready(self):
await client.change presence(status=discord.Status.idle, activity=discord.Game('using f.'))
print('Bot is online.')
def setup(client):
client.add_cog(OnReady(client))
You're using self.client when you create the OnReady class, so use this instead of self.bot. You also don't need to pass anything to the on_ready event, so it becomes async def on_ready(self):
import discord
from discord.ext import commands
class OnReady(commands.Cog):
def __init__(self, client):
self.client = client
#commands.Cog.listener()
async def on_ready(self):
await self.client.change_presence(status=discord.Status.idle, activity=discord.Game('using f.'))
print('Bot is online.')
def setup(client):
client.add_cog(OnReady(client))

Categories