Discord.py - Previous function affects the next function - python

I am trying to make a discord bot using Python and I want to make it so not everyone can mention #everyone or when they do the message will be deleted immediately, but then I have another code ($snipe) which doesn't work until I delete it, and after I do, it gives me the response! Any help would be appreciated!
#client.event
async def on_message(message):
xall = "#everyone"
role1 = discord.utils.get(message.guild.roles, name = "Owner")
role2 = discord.utils.get(message.guild.roles, name="Mod")
roles = role1 or role2
if xall in message.content:
if roles in message.author.roles:
pass
else:
await message.delete(message)
#Fun
#/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#client.command()
async def snipe(ctx):
await ctx.send("Aight, imma go snipe!")
#client.command()
async def slap(ctx, members: commands.Greedy[discord.Member], *, reason='no reason'):
slapped = ", ".join(x.mention for x in members)
await ctx.send('{} just got slapped for {}'.format(slapped, reason))

import discord
from discord.ext import commands
client = discord.Client()
#client.event
async def on_message(msg):
owner = discord.utils.get(msg.guild.roles, name="Owner")
mod = discord.utils.get(msg.guild.roles, name="Mod")
roles = (owner, mod)
if msg.mention_everyone:
if not any(r in msg.author.roles for r in roles):
await msg.delete()
client.run(TOKEN)
I have just ran this, and this works as expected. Removes the message if needed.

Related

No error but it is not running HELP Discord.py

i want to make a discord bot but i cant run it.
idk what to do
it just runs
and no log
idk REALLY what to do
import discord
from discord.ext import commands
import os
import keep_alive
client = commands.Bot(command_prefix="!")
token = os.environ.get('Token')
GUILD = os.environ.get('Guild')
async def on_ready():
print(f'{client.user} is connected')
#client.command()
async def dm(ctx, member: discord.Member):
await ctx.send('what do u want to say bitch!')
def check(m):
return m.author.id == ctx.author.id
massage = await client.wait_for('massage', check=check)
await ctx.send(f'send massage to {member} ')
await member.send(f'{ctx.member.mention} has a massage for you: \n {massage}')
#client.event
async def on_member_join(member):
channel = discord.util.get(member.Guild, name='general')
await channel.send(f'Hey welcome to my server {member.mention}, hope you enjoy this server!')
keep_alive.keep_alive()
client.run(token)
client.close()
i dont know what to do anymore
I tried everything i could i ran it in pycharm
vscode
nothing works
There's a lot of errors on your code. so I fixed it
First thing is your client events, keep_alive, client.run, also why did you put client.close()
import os, discord
import keep_alive
from discord.ext import commands
client = commands.Bot(command_prefix="!")
token = os.environ.get('Token')
GUILD = os.environ.get('Guild')
#client.event # You need this event
async def on_ready():
print(f'{client.user} is connected')
"""
client.wait_for('massage') is invalid. Changed it into 'message'. Guess it is a typo.
You can replace this command with the new one below.
"""
#client.command()
async def dm(ctx, member: discord.Member):
await ctx.send('what do u want to say bitch!')
def check(m):
return m.author.id == ctx.author.id
massage = await client.wait_for('message', check=check)
await ctx.send(f'send massage to {member} ')
await member.send(f'{ctx.member.mention} has a massage for you: \n {massage}')
"""
I also moved this on_member_join event outside because it blocks it.
"""
#client.event
async def on_member_join(member):
channel = discord.util.get(member.Guild, name='general')
await channel.send(f'Hey welcome to my server {member.mention}, hope you enjoy this server!')
"""
I put the keep_alive call outside because the function blocks it in your code.
And also removed client.close() to prevent your bot from closing
"""
keep_alive.keep_alive()
client.run(token)
For the dm command. Here it is:
#client.command()
async def dm(ctx, member:discord.Member=None):
if member is None:
return
await ctx.send('Input your message:')
def check(m):
return m.author.id == ctx.author.id and m.content
msg = await client.wait_for('message', check=check) # waits for message
if msg:
await member.create_dm().send(str(msg.content)) # sends message to user
await ctx.send(f'Message has been sent to {member}\nContent: `{msg.content}`')
Sorry, I'm kinda bad at explaining things, also for the delay. I'm also beginner so really I'm sorry

"commands" is not defined in discord.py

Code:
import os
import discord
import random
from discord.ext import commands
GUILD = os.getenv('DISCORD_GUILD')
client2 = commands.Bot(command_prefix = '')
#client.event
async def on_ready():
for guild in client.guilds:
if guild.name == GUILD:
break
print(
f'{client.user} has connected to '
f'{guild.name}'
)
#client.event
async def on_ready():
print(f'{client.user.name} has connected to Discord!')
bot = commands.Bot(command_prefix='$')
#client2.command(pass_context = True)
async def mute(ctx, member: discord.Member):
if ctx.message.author.server_permissions.administrator or ctx.message.author.id == '194151340090327041':
role = discord.utils.get(member.server.roles, name='Muted')
await bot.add_roles(member, role)
embed=discord.Embed(title="User Muted!", description="**{0}** was muted by **{1}**!".format(member, ctx.message.author), color=0xff00f6)
await bot.say(embed=embed)
else:
embed=discord.Embed(title="Permission Denied.", description="You don't have permission to use this command.", color=0xff00f6)
await bot.say(embed=embed)
client.run(os.getenv('TOKEN'))
I am trying to create a bot that mutes people. This is my 1st week in learning the discord API. I copied the mute function from a website so I didn't code everything myself. I'm having some trouble with the command. The error is:
NameError: name 'commands' is not defined
But I have seen other people do this and not get an error so I have no idea what the problem is.
Thanks a lot!
As mentioned before, you are going around with definitions that don't exist/that you shouldn't use.
First: Decide between client or bot and use the original handling, not somehow client2 etc.
Second: To use the commands, import from discord.ext import commands.
Third: Since you are now using client the commands have to be adapted. Also you don't use client.say or bot.say anymore, but ctx.send.
Fourth: You can't use multiple on_ready events, combine them or just use one.
Fifth: Please have a look at the mute command as yours contained many errors and requested things in the wrong way. You can take a look at other StackOverflow questions and answers as just copy and pasting another answer is not really useful...
Have a look at the full/final code:
from discord.utils import get # New import
import discord
from discord.ext import commands # New import
client = commands.Bot(command_prefix = 'YourPrefixHere') # Changes
TOKEN = "YourTokenHere" # Changes
#client.event
async def on_ready():
print(f'{client.user.name} has connected to Discord!')
#client.command()
async def mute(ctx, member: discord.Member):
if ctx.message.author.guild_permissions.administrator or ctx.message.author.id == 'Your_ID': # Changes
role = discord.utils.get(ctx.guild.roles, name='Muted') # Changes
await member.add_roles(role)
embed = discord.Embed(title="User Muted!",
description="**{}** was muted by **{}**!".format(member, ctx.message.author),
color=0xff00f6)
await ctx.send(embed=embed)
else:
embed=discord.Embed(title="Permission Denied.", description="You don't have permission to use this command.", color=0xff00f6)
await ctx.send(embed=embed)
client.run(TOKEN) # Changes

Python: AttributeError: 'Client' object has no attribute 'command'

Good afternoon! I am new to Python , and I am working on a discord bot. I keep suffering from this error: AttributeError: 'Client' object has no attribute 'command'. I tried everything to repair this, but I did not know. Any help would be fine. Please help me!
Here is the code:
import discord
import random
from discord.ext import commands
class MyClient(discord.Client):
client = commands.Bot(command_prefix = '?')
# Start
async def on_ready(self):
print('Logged on as', self.user)
# Latency
client = discord.Client()
#client.command()
async def ping(ctx):
await ctx.send(f'Pong! {round(client.latency * 1000)}ms')
# 8ball
#client.command(aliases=['8ball'])
async def _8ball(ctx, *, question):
responses = ['Biztosan.',
'Nagyon kétséges.']
await ctx.send(f'Kérdés: {question}\nVálasz: {random.choice(responses)}')
# Clear
#client.command()
async def clear(ctx, amount=5):
await ctx.channel.purge(limit=amount)
await ctx.send(f'Kész!')
async def on_message(self, message):
word_list = ['fasz', 'kurva', 'anyad', 'anyád', 'f a s z', 'seggfej', 'buzi', 'f.a.s.z', 'fa sz', 'k U.rv# any#dat']
if message.author == self.user:
return
messageContent = message.content
if len(messageContent) > 0:
for word in word_list:
if word in messageContent:
await message.delete()
await message.channel.send('Ne használd ezt a szót!')
messageattachments = message.attachments
if len(messageattachments) > 0:
for attachment in messageattachments:
if attachment.filename.endswith(".dll"):
await message.delete()
await message.channel.send("Ne küldj DLL fájlokat!")
elif attachment.filename.endswith('.exe'):
await message.delete()
await message.channel.send("Ne csak parancsikont küldj!")
else:
break
client = MyClient()
client.run(token)
There are a multitude of ways to make your bot, and it seems you tried to mash 2 ways of making it together.
Option 1: using the pre-made commands bot class
client = commands.Bot(command_prefix = '?')
client.command()
async def command_name(ctx, argument):
#command function
client.run(token)
Option 2: making you own subclass of client
class MyClient(discord.Client):
async def on_message(self, message):
if message.content.startswith('command_name'):
#command functionality
client = MyClient()
client.run()
You can use either of the two options, but not both at the same time (you could actually do that, but not in the way you did)
Also I would advice staying away from discord.py to learn python as asyncio is pretty complex
Why don't you simply define client like this?
client = commands.Bot(...)
Also you have defined it a couple of times in the code, delete them all and define it only ONCE at the top of the code after the imports. This is a really bad question, you should learn a lot more python before diving deeper into discord.py.

Disocrd.py command

I am coding a discord bot and i think there has got to be a much easier/ simpler way to detect messages using the prefix for commands (and easy to expand in future), my code at the moment just scans each message to see if it contains the exact command, maybe a class will help?
#client.event
async def on_message(message):
# print message content
print(message.content)
# if the message came from the bot ignore it
if message.author == client.user:
return
# if the message starts with "!repeat" then say the message in chat
if message.content.startswith("!repeat"):
sentmessage = message.content.replace("!repeat", "")
await message.channel.send(sentmessage)
if "hello" in message.content.lower():
await message.channel.send("Hello!")
if message.content.startswith("!cleanup"):
if not message.author.guild_permissions.administrator:
await message.channel.send("You do not have permission to run this command!")
else:
num2c = 0
num2c = int(message.content.replace("!cleanup", ""))+1
print(num2c)
await message.channel.purge(limit=num2c)
num2c = num2c-1
cleanmessage = str("Cleared "+str(num2c)+" Messages.")
await message.channel.send(cleanmessage, delete_after=5)
You can use commands.Bot, it has a built-in command system, here's an example:
import discord
from discord.ext import commands
# enabling intents
intents = discord.Intents.default()
bot = commands.Bot(command_prefix='!', intents=intents)
#bot.command()
async def foo(ctx, *args):
await ctx.send('whatever')
# You also have all the functionality that `discord.Client` has
#bot.event
async def on_message(message):
# ...
# you always need to add this when using `commands.Bot`
await bot.process_commands(message)
bot.run('token')
Take a look at the introduction

How do you create a new role in discord.py?

I have the following function in my bot to create x empty new roles (for this example I'll make it all the bot does):
import discord
from discord.ext import commands
CLIENT = commands.Bot(command_prefix='$')
#CLIENT.event
async def on_ready():
"""triggers when bot is running"""
print("Bot online")
#CLIENT.command(pass_context=True)
async def role(ctx, x=1):
"""creates x roles"""
guild = ctx.guild
for i in range(x):
await guild.create_role(name="new role")
print("created " + str(x) + " roles")
CLIENT.run("token")
The bot doesn't create the new roles or print out the message. (no output to the console at all, its as if the function had just said pass) What did I do wrong?
ctx.guild is None because you didn't enable intents.guilds to fix that you need to enable some basic intents, also you should typehint the x arg so it's converted to an integer.
intents = discord.Intents.default()
CLIENT = commands.Bot(..., intents=intents)
#CLIENT.command()
async def role(ctx, x: int=1):
for i in range(x):
await ctx.guild.create_role(f'new role {i}')
print(f"Created {x} roles")

Categories