Discord Bot Joining Message is not working python - 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')

Related

Why ctx.send(arg) doesn't send arg in Discord?

I just started making my own Discord bot, but even this simple test code won't work
import discord
from discord.ext import commands
intents = discord.Intents.default()
intents.message_content = True
client = discord.Client(intents=intents)
#client.event
async def on_ready():
print(f'We have logged in as {client.user}')
bot = commands.Bot(command_prefix='?',intents=intents)
#bot.command()
async def test(ctx, arg):
await ctx.send(arg)
Both
message.content.startswith('$hello'):
and
await message.channel.send('Hello!')
work as expected, I have tried to change the command_prefix to other symbols, with no luck
I think your issue might be related to having both a discord.Client and a discord.Bot class instantiated together. You only need one or the other - not both. It's not shown but I'm taking a hunch that you're doing client.run(TOKEN) and therefore, the command isn't getting registered.
import discord
from discord.ext import commands
intents = discord.Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix='?',intents=intents)
#bot.event
async def on_ready():
print(f'We have logged in as {bot.user}')
#bot.command()
async def test(ctx, arg):
await ctx.send(arg)
bot.run(TOKEN)
This ran perfectly for me.

A Python discord bot not responding to a command

I tried making a discord bot and stumbled across an issue, the bot does not respond to commands and I have no clue what's wrong.
Here's my code
import discord
from discord.ext import commands
class MyClient(discord.Client):
async def on_ready(self):
print('Logged on as {0}!'.format(self.user))
await client.change_presence(activity=discord.Game(name="Python"))
async def on_message(self, message):
print('Message from {0.author}: {0.content}'.format(message))
await bot.process_commands(message)
client = MyClient()
client.run("Token Here")
bot = commands.Bot(command_prefix='!')
#bot.command()
async def test(ctx):
await ctx.send("Sup")
You are currently mixing a discord.Client with a commands.bot.
Discord.py provides multiples ways to creates bots that are not compatibles each other.
Moreover, client.run is blocking, and should be at the end of your script.!
import discord
from discord.ext import commands
class MyClient(commands.Bot):
async def on_ready(self):
print('Logged on as {0}!'.format(self.user))
await client.change_presence(activity=discord.Game(name="Python"))
async def on_message(self, message):
print('Message from {0.author}: {0.content}'.format(message))
await self.process_commands(message)
client = MyClient(command_prefix='!')
#client.command()
async def test(ctx):
await ctx.send("Sup")
client.run("...")
Note that you are not obligated to subclass the commands.Bot class given by the library.
Here is an other exemple that don't use subclassing:
import discord
from discord.ext import commands
client = commands.Bot(command_prefix='!')
#client.event
async def on_ready():
print('Logged on as {0}!'.format(client.user))
await client.change_presence(activity=discord.Game(name="Python"))
#client.event
async def on_message(message):
print('Message from {0.author}: {0.content}'.format(message))
await client.process_commands(message)
#client.command()
async def test(ctx):
await ctx.send("Sup")
client.run("...")
Using the second approach might be beneficial if you just started to learn dpy, and can work when you dont have a lot of commands.
However, for bigger projects, the first approach will help to organise your bot by using cogs for commands and events.

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))

on message event make my bot don't working

My commands don't work and I think it's because of the on_message event. When it checks if message is in the good channel, it actually "steel" the command so my bot commands are not triggered but I don't know how to fix that
import discord, os
from discord.ext import commands
intents = discord.Intents.default()
intents.members = True
bot = commands.Bot(command_prefix='.',intents=intents)
defrole = ""
cmdchannels = ["none"]
#bot.event
async def on_ready():
print(f'{bot.user.name} has connected to Discord!')
await bot.change_presence(activity=discord.Game('.help'))
#bot.event
async def on_member_join(member):
await member.add_roles(discord.utils.get(member.guild.roles, name=defrole))
#bot.event
async def on_message(message):
if message.channel.id in cmdchannels :
await message.delete()
#bot.command()
async def setcmd(ctx, arg):
global cmdchannels
cmdchannels.append(discord.utils.get(ctx.guild.channels, name=arg).id)
print(cmdchannels)
await ctx.send(arg+' is now defined as a cmd/bot channel !')
#bot.command()
async def defaultrole(ctx):
global defrole
defrole = str(ctx.message.role_mentions[0])
await ctx.send(defrole+' is now the default on join role !')
bot.run("Token")
You will need to process the commands, add this line at the end of your on_message function:
await bot.process_commands(message)
Reference: process_commands()
on_message event blocks your commands from working. In order to prevent this, you have to process commands.
#bot.event
async def on_message(message):
if message.channel.id in cmdchannels :
await message.delete()
await bot.process_commands(message)

Discord Bot Command is not Showing

So I'm making a basic bot command that responds with what the player said, like doing !test code will make the bot respond with 'code'. For some reason, nothing happens when the command is run. I even put a print inside of it to see if it was actually being run, and it wasn't. Here's my code:
import discord
from discord.ext import commands
client = discord.Client()
bot = commands.Bot(command_prefix="!")
#client.event
async def on_ready():
print('Logged in as {0.user}'.format(client))
print("-"*16)
game = discord.Game("Discord")
await client.change_presence(status=discord.Status.online, activity=game)
#bot.command()
async def test(ctx, arg):
await ctx.send(str(arg))
client.run('token here')
Any help is appreciated.
try this out:
import discord
from discord.ext import commands
client = commands.Bot(command_prefix="!")
#client.event
async def on_ready():
print('Logged in as {0.user}'.format(client))
print("-"*16)
game = discord.Game("Discord")
await client.change_presence(status=discord.Status.online, activity=game)
#client.command()
async def test(ctx, *, arg):
await ctx.send(str(arg))
client.run('token here')
heres what you got wrong:
client = discord.Client()
bot = commands.Bot(command_prefix="!")
You had 2 separate handlers for the bot, if you use commands you only need the bot = commands.Bot(command_prefix="!") line, in this case you had the bot handler for commands but you were running client
The code below runs as expected when tested using Python3.7 ...
import discord
from discord.ext import commands
client = commands.Bot(command_prefix="!")
#client.event
async def on_ready():
print('Logged in as {0.user}'.format(client))
print("-"*16)
game = discord.Game("Discord")
await client.change_presence(status=discord.Status.online, activity=game)
#client.command()
async def test(ctx, *arg):
await ctx.send(str(arg))
client.run('token here')
Your code as posted has an await statement outside of a function
......
print("-"*16)
game = discord.Game("Discord")
await client.change_presence(status=discord.Status.online, activity=game)
.......
Also change
#bot.command()
async def test(ctx, arg):
TO:
#bot.command()
async def test(ctx, *arg):
For an explanation as to why you pass *arg and not arg:
args-and-kwargs
You can't run client and bot together if want bot to run the last line of code must be bot.run('your token') if you want client to run use client.run('your token')

Categories