modmail system discord.py no response to reaction - python

so i was making a discord bot and made a modmail system and got this error. can someone plz help and tell me where i am going wrong i searched many similar errors but didnt find the answer.
bot:
import random
import os
import sys
import asyncio
from discord.ext import commands
intents = discord.Intents.default()
intents.members = True
client = commands.Bot(command_prefix='-', intents=intents)
client.remove_command("help")
#client.event
async def on_ready():
await client.change_presence(status=discord.Status.idle, activity=discord.Game('Do -help'))
print('functioning...')
#client.event
async def on_member_join(member):
print(f'{member} has joined the server.')
await member.create_dm()
await member.dm_channel.send(f'Hi {member.mention}, welcome to my Discord server!')
#client.event
async def on_member_remove(member):
print(f'{member} has left the server.')
for filename in os.listdir("./cogs"):
if filename.endswith(".py"):
client.load_extension(f'cogs.{filename[:-3]}')
#client.command(brief="Load", help="Loading cogs")
async def load(ctx, extension):
client.load_extension(f'cogs.{extension}')
#client.command(brief="Unload", help="Unloading cogs")
async def unload(ctx, extension):
client.unload_extension(f'cogs.{extension}')
#client.command(brief="Ping", help="The time it takes for a small data set to be transmitted from your device to a server on the Internet and back to your device again.")
async def ping(ctx):
await ctx.send(f'Pong! {round(client.latency*1000)}ms')
#client.command(aliases=['test','8ball', 'future'], brief="8ball", help="A little fun game.")
async def _8ball(ctx, *,question):
responses=[ "It is certain.",
"It is decidedly so.",
"Without a doubt.",
"Yes definitely.",
"You may rely on it.",
"As I see it, yes.",
"Most likely.",
"Outlook good.",
"Yes.",
"Signs point to yes.",
"Reply hazy, try again.",
"Ask again later.",
"Better not tell you now.",
"Cannot predict now.",
"Concentrate and ask again.",
"Don't count on it.",
"My reply is no.",
"My sources say no.",
"Outlook not so good.",
"Very doubtful."]
await ctx.send(f'Question: {question}\nAnswer: {random.choice(responses)}')
#client.command(aliases=['purge','clean'], brief="Purge", help="Clears a fixed number of messahes.")
#commands.has_permissions(manage_messages=True)
async def clear(ctx, amount=5):
await ctx.channel.purge(limit=amount)
#client.command(brief="Kick", help="Kicks a person out of the guild.")
#commands.has_permissions(manage_messages=True)
async def kick(ctx, member:discord.Member, *, reason=None):
message = f"You have been kicked from {ctx.guild.name}, reason: {reason}"
await member.send(message)
await member.kick(reason=reason)
await ctx.send(f'Kicked {member.mention}')
#client.command(brief="Ban", help="Bans a person in the guild.")
#commands.has_permissions(manage_messages=True)
async def ban(ctx, member:discord.Member, *, reason=None):
message = f"You have been banned from {ctx.guild.name}, reason: {reason}"
await member.send(message)
await member.ban(reason=reason)
await ctx.send(f'Banned {member.mention}')
#client.command(brief="Unban", help="Unbans a banned person in the guild.")
#commands.has_permissions(manage_messages=True)
async def unban(ctx, *, user=None):
try:
user = await commands.converter.UserConverter().convert(ctx, user)
except:
await ctx.send("Error: user could not be found!")
return
try:
bans = tuple(ban_entry.user for ban_entry in await ctx.guild.bans())
if user in bans:
await ctx.guild.unban(user, reason="Responsible moderator: "+ str(ctx.author))
else:
await ctx.send("User not banned!")
return
except discord.Forbidden:
await ctx.send("I do not have permission to unban!")
return
except:
await ctx.send("Unbanning failed!")
return
await ctx.send(f"Successfully unbanned {user.mention}!")
class DurationConverter(commands.Converter):
async def convert(self, ctx, argument):
amount=argument[:-1]
unit=argument[-1]
if amount.isdigit() and unit in ['s','m','h','d']:
return(int(amount),unit)
raise commands.BadArgument(message="Not a valid duration")
#client.command(brief="Tempban", help="Temporarily bans a person in the guild.")
#commands.has_permissions(manage_messages=True)
async def tempban(ctx, member: commands.MemberConverter, duration: DurationConverter):
multiplier={'s':1, 'm':60, 'h':3600, 'd':86400}
amount, unit= duration
message = f"You have been banned from {ctx.guild.name}, for {amount}{unit}"
await member.send(message)
await ctx.guild.ban(member)
await ctx.send(f'{member.mention} has been banned for {amount}{unit}')
await asyncio.sleep(amount*multiplier[unit])
await ctx.guild.unban(member)
#client.command(brief="Tempmute", help="Temporarily mutes a person in the guild.")
#commands.has_permissions(manage_messages=True)
async def tempmute(ctx, member: discord.Member, duration: DurationConverter, reason=None):
multiplier = {'s': 1, 'm': 60, 'h': 3600, 'd': 86400}
amount, unit = duration
guild = ctx.guild
muteRole = discord.utils.get(guild.roles, name="Muted")
await member.add_roles(muteRole, reason=reason)
await ctx.send(f"{member.mention} has been muted in {ctx.guild} for {amount}{unit}")
await member.send(f"You have been muted in {ctx.guild} for {amount}{unit}")
await asyncio.sleep(amount*multiplier[unit])
await member.remove_roles(muteRole, reason=reason)
await ctx.send(f"{member.mention} has been unmuted in {ctx.guild} ")
await member.send(f"You have been unmuted in {ctx.guild} ")
def restart_bot():
os.execv(sys.executable, ['python'] + sys.argv)
#client.command(name= 'restart', brief="Restart", help="Restarts the bot.")
async def restart(ctx):
await ctx.send("Restarting bot...")
restart_bot()
#client.command( brief="Connects", help="Connects the bot.")
async def connect(self):
print(" bot connected")
#client.command(brief="Disconnects", help="Disconnects the bot.")
async def disconnect(self):
print("bot disconnected")
#client.command(brief="Mute", help="Mutes a person in the guild.")
#commands.has_permissions(manage_messages=True)
async def mute(ctx, member: discord.Member, *, reason=None):
guild = ctx.guild
muteRole = discord.utils.get(guild.roles, name="Muted")
if not muteRole:
await ctx.send("No Mute Role found! Creating one now...")
muteRole = await guild.create_role(name="Muted")
for channel in guild.channels:
await channel.set_permissions(muteRole, speak=False, send_messages=False, read_messages=True,
read_message_history=True)
await member.add_roles(muteRole, reason=reason)
await ctx.send(f"{member.mention} has been muted in {ctx.guild} | Reason: {reason}")
await member.send(f"You have been muted in {ctx.guild} | Reason: {reason}")
#client.command(brief="Unmute", help="Unmutes a muted person in the guild.")
#commands.has_permissions(manage_messages=True)
async def unmute(ctx, member: discord.Member, *, reason=None):
guild = ctx.guild
muteRole = discord.utils.get(guild.roles, name="Muted")
await member.remove_roles(muteRole, reason=reason)
await ctx.send(f"{member.mention} has been unmuted in {ctx.guild}")
await member.send(f"You have been unmuted in {ctx.guild}")
#client.command(brief="Slowmode", help="Enables a rate limit per message.")
#commands.has_permissions(manage_messages=True)
async def slowmode(ctx, time:int):
if (not ctx.author.guild_permissions.manage_messages):
await ctx.send('Cannot run command! Requires: ``Manage Messages``')
return
if time == 0:
await ctx.send('Slowmode is currently set to `0`')
await ctx.channel.edit(slowmode_delay = 0)
elif time > 21600:
await ctx.send('You cannot keep the slowmode higher than 6 hours!')
return
else:
await ctx.channel.edit(slowmode_delay = time)
await ctx.send(f"Slowmode has been set to `{time}` seconds!")
#client.command(brief="Prefix", help="Changes the prefix.")
async def setprefix(ctx, prefix):
client.command_prefix = prefix
await ctx.send(f"Prefix changed to ``{prefix}``")
#client.command(brief="Avatar", help="Displays a guild members pfp.")
async def avatar(ctx, member: discord.Member = None):
if member == None:
member = ctx.author
icon_url = member.avatar_url
avatarEmbed = discord.Embed(title=f"{member.name}\'s Avatar", color=0x802BAE)
avatarEmbed.set_image(url=f"{icon_url}")
avatarEmbed.timestamp = ctx.message.created_at
await ctx.send(embed=avatarEmbed)
client.run(token)
modmail:
import discord
import asyncio
from discord.ext.commands import Cog
client = discord.Client()
sent_users = []
class modmail(Cog):
def __init__(self, bot):
self.bot = bot
#Cog.listener()
async def on_message(self,message):
if message.guild: # ensure the channel is a DM
return
if message.author.bot:
return
if message.author == client.user:
return
if message.author.id in sent_users: # Ensure the intial message hasn't been sent before
return
modmail_channel = discord.utils.get(client.get_all_channels(), name="modmail")
embed = discord.Embed(color=0x00FFFF)
embed.set_author(name=f"Modmail System",
icon_url="https://cdn.discordapp.com/icons/690937143522099220/34fbd058360c3d4696848592ff1c5191.webp?size=1024")
embed.add_field(name='Report a member:', value=f"React with 1️⃣ if you want to report a member.")
embed.add_field(name='Report a Staff Member:', value=f"React with 2️⃣ if you want to report a Staff Member.")
embed.add_field(name='Warn Appeal:', value=f"React with 3️⃣ if you would like to appeal a warning.")
embed.add_field(name='Question:',
value=f"React with 4️⃣ if you have a question about our moderation system or the server rules.")
embed.set_footer(text="Modmail")
msg = await message.channel.send(embed=embed)
await msg.add_reaction("1️⃣")
await msg.add_reaction("2️⃣")
await msg.add_reaction("3️⃣")
await msg.add_reaction("4️⃣")
sent_users.append(message.author.id) # add this user to the list of sent users
try:
def check(reaction, user):
return user == message.author and str(reaction.emoji) in ["1️⃣", "2️⃣", "3️⃣", "4️⃣"]
reaction, user = await client.wait_for("reaction_add", timeout=60, check=check)
if str(reaction.emoji) == "1️⃣":
embed = discord.Embed(color=0x00FFFF)
embed.set_author(name=f"Modmail System",
icon_url="https://cdn.discordapp.com/icons/690937143522099220/34fbd058360c3d4696848592ff1c5191.webp?size=1024")
embed.add_field(name='How to Report:',
value="Send the ID of the person you are reporting and attach add a screen shot of them breaking a rule (can be ToS or a server rule).")
embed.set_footer(text="Report a member ")
await message.author.send(embed=embed)
message = await client.wait_for("message", timeout=60, check=lambda
m: m.channel == message.channel and m.author == message.author)
embed = discord.Embed(title=f"{message.content}", color=0x00FFFF)
await modmail_channel.send(embed=embed)
except asyncio.TimeoutError:
await message.channel.send("Reaction timeout!!!")
#Cog.listener()
async def on_ready(self):
print("modmail ready")
def setup(bot):
bot.add_cog(modmail(bot))
logcog:
import discord
import datetime
from datetime import datetime
from discord.ext.commands import Cog
class Example(Cog):
def __init__(self, client):
self.client = client
#Cog.listener()
async def on_ready(self):
print("log ready")
#Cog.listener()
async def on_message(self, message):
if not message.guild:
pass
else:
if not message.content and message.channel:
pass
else:
channel = discord.utils.get(message.guild.channels, name='log')
embed = discord.Embed(title="Message sent", description=message.author, color=message.author.color,
timestamp=datetime.utcnow())
embed.add_field(name="Message Sent", value=message.content, inline=True)
embed.add_field(name="Channel Sent", value=message.channel, inline=True)
await channel.send(embed=embed)
#Cog.listener()
async def on_message_edit(self, before, after):
if len(before.content)==0 and len(after.content)==0 and len(before.channel)==0:
pass
elif not before.guild:
pass
else:
channel = discord.utils.get(before.guild.channels, name='log')
embed = discord.Embed(title="Message edited", description=before.author, color=before.author.color,
timestamp=datetime.utcnow())
embed.add_field(name="Before edit", value=before.content, inline=True)
embed.add_field(name="After edit", value=after.content, inline=True)
embed.add_field(name="Channel Sent", value=before.channel, inline=True)
await channel.send(embed=embed)
#Cog.listener()
async def on_message_delete(self, message):
if not message.content and message.channel:
pass
elif not message.guild:
pass
else:
channel = discord.utils.get(message.guild.channels, name='log')
embed = discord.Embed(title="Message deleted", description=message.author, color=message.author.color,
timestamp=datetime.utcnow())
embed.add_field(name="Deleted Message", value=message.content, inline=True)
embed.add_field(name="The channel is", value=message.channel, inline=True)
await channel.send(embed=embed)
def setup(client):
client.add_cog(Example(client))
so when i run this code i get the reaction message and embed in the dm but when i click on the reaction i get no further out put and after 60s a message comes reaction timeout. I dont get any error message either.

So I finally solved the problem, which stemmed from the intents setup. In my main file I used this code:
intents = discord.Intents.default()
intents.members = True
bot = commands.Bot(command_prefix='!', intents=intents)
bot.load_extension("cogs.maincog")
bot.run(token)
You may want to do this slightly differently (like by using client), but the important part is the intents. This is apparently because the privileged intent "members" is required when testing for reactions is direct messages. I replaced the client with the Bot class, so the testing function became:
reaction, user = await self.bot.wait_for("reaction_add", timeout=60, check=check)
As far as I have tested, this should work perfectly well but let me know if you have any problems or want me to link the full code.
Edit: Look at how to enable privileged intents here.

Related

discord.py bot crashes after a few hours

it crashes with a very long error message about the token but the token isnt the problem as it worked for the past couple of hours, when it crashes i go to the console and type kill 1, it work fine after that but after a few hours it does it again. this is a bot that is written on replit.
i was wondering if there was a way to make it stay online without crashing (i am using uptimerobot already)
here is the code
#imports#######################################################################################################################imports#
import discord
from discord.ext import commands, tasks
from discord.utils import get
from replit import db
import random
from itertools import cycle
import keep_alive
import os
#starting#####################################################################################################################starting#
status = cycle(['.help', '..help'])
intents = discord.Intents.default()
intents.members = True
client = commands.Bot(command_prefix='.', intents=discord.Intents.all())
client.remove_command('help')
async def change_status():
await client.change_presence(activity=discord.Game(next(status)))
#client.event
async def on_ready():
client.loop.create_task(change_status())
print("CYKLERBOT is ready, you can now leave the tab")
#member-update###########################################################################################################member-update#
#client.event
async def on_member_join(member):
print(f'{member} has joined a server.')
#client.event
async def on_member_remove(member):
print(f'{member} has left a server')
#economy###################################################################################################################economy#
#client.command()
async def balance(ctx, *, user):
await ctx.channel.purge(limit=1)
value = db["m" + user]
await ctx.send(f'{user}, your balance is ${value}')
print(value)
print(user)
#client.command(aliases=['create'])
#commands.has_permissions(administrator=True)
async def createwallet(ctx, *, user):
await ctx.channel.purge(limit=1)
db["m" + user] = 0
await ctx.send(f'{user}s wallet has been created')
#client.command(aliases=['add'])
#commands.has_permissions(administrator=True)
async def addmoney(ctx, user, *, amount: int):
await ctx.channel.purge(limit=1)
value = db["m" + user]
db["m" + user] = value + amount
await ctx.send(f'{amount} has been added to {user}s wallet')
#client.command(aliases=['set'])
#commands.has_permissions(administrator=True)
async def setmoney(ctx, user, *, amount: int):
await ctx.channel.purge(limit=1)
db["m" + user] = amount
await ctx.send(f'{user}s wallet had been set to {amount}')
#client.command(aliases=['remove'])
#commands.has_permissions(administrator=True)
async def removemoney(ctx, user, *, amount: int):
await ctx.channel.purge(limit=1)
value = db["m" + user]
db[user + 'm'] = value - amount
await ctx.send(f'{amount} has been removed from {user}s wallet')
#client.command()
#commands.has_permissions(administrator=True)
async def delete(ctx, *, user):
await ctx.channel.purge(limit=1)
del db[user]
await ctx.send(f'{user}s account has been deleted')
#client.command(aliases=['wkeys'])
#commands.has_permissions(administrator=True)
async def walletkeys(ctx):
await ctx.channel.purge(limit=1)
matches = db.prefix("m")
await ctx.send(f'{matches}')
#inventory###################################################################################################################inventory#
#client.command(aliases=['createi'])
#commands.has_permissions(administrator=True)
async def createinventory(ctx, *, user):
await ctx.channel.purge(limit=1)
db['i' + user] = []
await ctx.send(f'{user}s inventory has been created')
#client.command(aliases=['inv'])
async def inventory(ctx, *, user):
await ctx.channel.purge(limit=1)
value = db['i' + user]
await ctx.send(f'{user}s inventory contains {value}')
#client.command(aliases=['give'])
#commands.has_permissions(administrator=True)
async def giveitem(ctx, user, *, item):
await ctx.channel.purge(limit=1)
value = db['i' + user]
value.append(item)
await ctx.send(f'{item}, has been added to {user}s inventory')
#client.command(aliases=['take'])
#commands.has_permissions(administrator=True)
async def takeitem(ctx, user, *, item):
await ctx.channel.purge(limit=1)
value = db['i' + user]
value.remove(item)
await ctx.send(f'{item}, has been removed from {user}s inventory')
#client.command(aliases=['ikeys'])
#commands.has_permissions(administrator=True)
async def inventorykeys(ctx):
await ctx.channel.purge(limit=1)
matches = db.prefix("i")
await ctx.send(f'{matches}')
#warnings###################################################################################################################warnings#
#client.command(aliases=['createww'])
#commands.has_permissions(administrator=True)
async def createwarnwallet(ctx, *, user):
await ctx.channel.purge(limit=1)
db['ww' + user] = []
await ctx.send(f'{user}s warn wallet has been created')
#client.command()
async def warnings(ctx, *, user):
await ctx.channel.purge(limit=1)
value = db['ww' + user]
await ctx.send(f'{user}s warn wallet contains {value}')
#client.command()
#commands.has_permissions(administrator=True)
async def warn(ctx, user, *, item):
await ctx.channel.purge(limit=1)
value = db['ww' + user]
value.append(item)
await ctx.send(f'{user} has been warned with {item}')
#client.command()
#commands.has_permissions(administrator=True)
async def dewarn(ctx, user, *, item):
await ctx.channel.purge(limit=1)
value = db['ww' + user]
value.remove(item)
await ctx.send(f'{user}s warning ({item}) has been removed')
#client.command(aliases=['warncount'])
#commands.has_permissions(administrator=True)
async def warningcount(ctx, *, user):
await ctx.channel.purge(limit=1)
value = db['ww' + user]
await ctx.send(f'{user} has {len(value)} warnings')
#client.command(aliases=['wwkeys'])
#commands.has_permissions(administrator=True)
async def warningkeys(ctx):
await ctx.channel.purge(limit=1)
matches = db.prefix("ww")
await ctx.send(f'{matches}')
#polls###########################################################################################################################polls#
#client.command()
async def poll(ctx, *, message):
await ctx.channel.purge(limit=1)
emb = discord.Embed(title=f"{message}",
description=f"asked by #{ctx.message.author}",
colour=random.choice(rcolor))
msg = await ctx.channel.send(embed=emb)
await msg.add_reaction('🟩')
await msg.add_reaction('🟥')
#client.command()
async def mpoll(ctx, *, message):
await ctx.channel.purge(limit=1)
emb = discord.Embed(title=f"{message}",
description=f"asked by #{ctx.message.author}",
colour=random.choice(rcolor))
msg = await ctx.channel.send(embed=emb)
await msg.add_reaction('🟩')
await msg.add_reaction('🟥')
await msg.add_reaction('🟧')
await msg.add_reaction('🟨')
await msg.add_reaction('🟦')
await msg.add_reaction('🟪')
await msg.add_reaction('🟫')
#fun###############################################################################################################################fun#
#client.command()
async def ping(ctx):
await ctx.channel.purge(limit=1)
await ctx.send(f'Pong! {round(client.latency * 1000)}ms')
#client.command(aliases=['8ball'])
async def _8ball(ctx, *, question):
await ctx.channel.purge(limit=1)
responces = [
'It is certain', 'It is decidedly so', 'Without a doubt',
'Yes definitely', 'You may rely on it', 'As I see it, yes',
'Most likely', 'Outlook good', 'Yes', 'Signs point to yes',
'Reply hazy, try again', 'Ask again later', 'Better not tell you now',
'Cannot predict now', 'Concentrate and ask again', 'Dont count on it',
'My reply is no', 'My sources say no', 'Outlook not so good',
'Very doubtful'
]
await ctx.send(f'Question: {question}\nAnswer: {random.choice(responces)}')
#client.command()
async def coinflip(ctx):
responces2 = [
'heads',
'tails',
]
await ctx.send(random.choice(responces2))
#client.command()
async def roll(ctx, amount1: int):
await ctx.channel.purge(limit=1)
await ctx.send(f'you rolled a {random.randrange(1, amount1 + 1)}')
#admin###########################################################################################################################admin#
#client.command()
#commands.has_permissions(manage_messages=True)
async def purge(ctx, amount: int):
await ctx.channel.purge(limit=amount)
#client.command()
#commands.has_permissions(manage_messages=True)
async def undo(ctx):
await ctx.channel.purge(limit=2)
#purge.error
async def purge_error(ctx, error):
if isinstance(error, commands.MissingRequiredArgument):
await ctx.send('ERROR MSG: ||please specify an amount of messages to delete||')
if isinstance(error, commands.MissingPermissions):
await ctx.send("ERROR MSG: ||You do not have the permission to use that command!||")
#client.command()
#commands.has_permissions(administrator=True)
async def kick(ctx, member: discord.Member, *, reason=None):
await ctx.channel.purge(limit=1)
await user.remove_roles("manager")
await member.kick(reason=reason)
await ctx.send(f'Kicked {member.mention} Reason: {reason}')
#kick.error
async def kick_error(ctx, error):
if isinstance(error, commands.MissingRequiredArgument):
await ctx.send('ERROR MSG: ||please specify the person to kick followed by the reason||')
if isinstance(error, commands.MissingPermissions):
await ctx.send("ERROR MSG: ||You do not have the permission to use that command!||")
#client.command()
#commands.has_permissions(administrator=True)
async def ban(ctx, member: discord.Member, *, reason=None):
await ctx.channel.purge(limit=1)
await user.remove_roles("manager")
await member.ban(reason=reason)
await ctx.send(f'Banned {member.mention} Reason: {reason}')
#ban.error
async def ban_error(ctx, error):
if isinstance(error, commands.MissingRequiredArgument):
await ctx.send('ERROR MSG: ||please specify the person to ban followed by the reason||')
if isinstance(error, commands.MissingPermissions):
await ctx.send("ERROR MSG: ||You do not have the permission to use that command!||")
#client.command()
#commands.has_permissions(administrator=True)
async def unban(ctx, *, member):
await ctx.channel.purge(limit=1)
banned_users = await ctx.guild.bans()
member_name, member_discriminator = member.split('#')
for ban_entry in banned_users:
user = ban_entry.user
if (user.name, user.discriminator) == (member_name,
member_discriminator):
await ctx.guild.unban(user)
await ctx.send(f'Unbanned {user.mention}')
return
#unban.error
async def unban_error(ctx, error):
if isinstance(error, commands.MissingRequiredArgument):
await ctx.send('ERROR MSG: ||please specify the person to unban followed by the tag||')
if isinstance(error, commands.MissingPermissions):
await ctx.send("ERROR MSG: ||You do not have the permission to use that command!||")
#client.command(pass_context = True)
#commands.has_permissions(manage_roles=True)
async def role(ctx, user : discord.Member, *, role : discord.Role):
await ctx.channel.purge(limit=1)
if role in user.roles:
await ctx.send(f'{user.mention} already had that role, {role}')
else:
await user.add_roles(role)
await ctx.send(f'{role} has been added to {user.mention}')
#role.error
async def role_error(ctx, error):
if isinstance(error, commands.MissingRequiredArgument):
await ctx.send('ERROR MSG: ||please specify the # that you would like to role followed by the role that you would like to give||')
if isinstance(error, commands.MissingPermissions):
await ctx.send("ERROR MSG: ||You do not have the permission to use that command!||")
#client.command(pass_context = True)
#commands.has_permissions(manage_roles=True)
async def derole(ctx, user : discord.Member, *, role : discord.Role):
await ctx.channel.purge(limit=1)
if role in user.roles:
await user.remove_roles(role)
await ctx.send(f'{role} has been removed from {user.mention}')
else:
await ctx.send(f'{user.mention} does not have this role{role}')
#derole.error
async def derole_error(ctx, error):
if isinstance(error, commands.MissingRequiredArgument):
await ctx.send('ERROR MSG: ||please specify the # that you would like to derole followed by the role that you would like to remove||')
if isinstance(error, commands.MissingPermissions):
await ctx.send("ERROR MSG: ||You do not have the permission to use that command!||")
#help command#############################################################################################################help command#
rcolor = [
discord.Colour.purple(),
discord.Colour.orange(),
discord.Colour.green(),
discord.Colour.blue(),
discord.Colour.red(),
discord.Colour.teal(),
discord.Colour.dark_teal(),
discord.Colour.dark_green(),
discord.Colour.dark_blue(),
discord.Colour.dark_purple(),
discord.Colour.magenta(),
discord.Colour.dark_magenta(),
discord.Colour.gold(),
discord.Colour.dark_gold(),
discord.Colour.dark_orange(),
discord.Colour.dark_red(),
discord.Colour.lighter_gray(),
discord.Colour.dark_gray(),
discord.Colour.light_gray(),
discord.Colour.darker_gray(),
discord.Colour.blurple(),
discord.Colour.greyple()
]
#client.command(pass_context=True)
async def help(ctx):
await ctx.channel.purge(limit=1)
embed = discord.Embed(colour=random.choice(rcolor))
embed.add_field(name='.ping',
value='Returns Pong! + the response time',
inline=False)
embed.add_field(name='.8ball [insert question here]',
value='returns a random yes/no type answer',
inline=False)
embed.add_field(name='.coinflip',
value='Returns heads or tails',
inline=False)
embed.add_field(
name='.roll [insert value here]',
value='Returns a random value from 1 to the specified number',
inline=False)
embed.add_field(name='.ping',
value='Returns Pong! + the response time',
inline=False)
embed.add_field(name='.poll, [insert question here]',
value='outputs an embed pole with automatic reactions',
inline=False)
embed.add_field(
name='.mpoll, [inset question here]',
value='outputs an embed pole with 7 automatic reactions',
inline=False)
embed.add_field(name='.balance [insert wallet user here]',
value='Returns the amount of money the wallet user has',
inline=False)
embed.add_field(name='.inventory [insert inventory user here]',
value='Returns all items that the user has',
inline=False)
embed.add_field(name='MOD ONLY!!! .modhelp',
value='hows .help with moderator commands',
inline=False)
await ctx.send(embed=embed)
#client.command(pass_context=True)
#commands.has_permissions(manage_messages=True)
async def modhelp(ctx):
await ctx.channel.purge(limit=1)
embed = discord.Embed(colour=random.choice(rcolor))
embed.add_field(name='.ban [insert # here], [insert reason here]',
value='bans specified member/bot for the specified reason',
inline=False)
embed.add_field(name='.unban [insert name here + tag]',
value='unbans specified member/bot',
inline=False)
embed.add_field(name='.purge [insert value here]',
value='removes the specified amount of messages (-1)',
inline=False)
embed.add_field(name='.undo',
value='removes the previous message',
inline=False)
embed.add_field(name='.kick [insert # here], [insert reason here]',
value='kicks specified member/bot for the specified reason',
inline=False)
embed.add_field(name='.role [insert # here], [insert role here]',
value='adds the specified role to the specified user',
inline=False)
embed.add_field(name='.derole [insert # here], [insert role here]',
value='removes the specified role from the specified user',
inline=False)
embed.add_field(name='.delete [insert user here]',
value='deletes the users wallet/inventory',
inline=False)
embed.add_field(name='.modhelpwarnings',
value='shows all moderator warning commands',
inline=False)
embed.add_field(name='.modhelpwallet',
value='shows all moderator warning commands',
inline=False)
embed.add_field(name='.modhelpinventory',
value='shows all moderator warning commands',
inline=False)
await ctx.send(embed=embed)
#client.command(pass_context=True)
#commands.has_permissions(manage_messages=True)
async def modhelpwarnings(ctx):
await ctx.channel.purge(limit=1)
embed = discord.Embed(colour=random.choice(rcolor))
embed.add_field(name='.createwarnwallet [insert warning user here]',
value='creates a warning wallet for the specified user',
inline=False)
embed.add_field(name='.warnings [insert warning user here]',
value='gives all the warnings of the specified user',
inline=False)
embed.add_field(name='.warn [insert warning user here] [insert violation here]',
value='adds the warning to the specified users wallet',
inline=False)
embed.add_field(name='.dewarn [insert warning user here] [insert violation here',
value='removes the specified warning from the specified user',
inline=False)
embed.add_field(name='.warncount [insert warning user here]',
value='give the amount of warnings the specified user has',
inline=False)
embed.add_field(name='.warningkeys',
value='gives all users that have a warning account',
inline=False)
await ctx.send(embed=embed)
#client.command(pass_context=True)
#commands.has_permissions(manage_messages=True)
async def modhelpwallet(ctx):
await ctx.channel.purge(limit=1)
embed = discord.Embed(colour=random.choice(rcolor))
embed.add_field(name='.create [insert wallet user here]',
value='creates a wallet for the specified user',
inline=False)
embed.add_field(name='.set [insert wallet user here], [insert amount here]',
value='sets the user wallet to given amount',
inline=False)
embed.add_field(name='.add [insert wallet user here], [insert amount here]',
value='adds the amount to the users wallet',
inline=False)
embed.add_field(name='.remove [insert wallet user here], [insert amount here]',
value='removes the amount from ths users wallet',
inline=False)
embed.add_field(name='.wkeys',
value='shows all users which have a wallet',
inline=False)
await ctx.send(embed=embed)
#client.command(pass_context=True)
#commands.has_permissions(manage_messages=True)
async def modhelpinventory(ctx):
await ctx.channel.purge(limit=1)
embed = discord.Embed(colour=random.choice(rcolor))
embed.add_field(name='.createi [insert inventory user here]',
value='creates an inventory for the specified user',
inline=False)
embed.add_field(name='.give [insert inventory user here]',
value='gives an item to the specified user',
inline=False)
embed.add_field(name='.take [insert inventory user here]',
value='removes an item from the specified user',
inline=False)
embed.add_field(name='.ikeys',
value='shows all users which have an inventory',
inline=False)
await ctx.send(embed=embed)
#end###############################################################################################################################end#
keep_alive.keep_alive()
client.run("TOKEN")
every time it crashes i type kill 1 in the console and it works. but it crashes again after a few hours.
i just hope that i can get it working 24/7 because the people on my server are getting annoyed

How to add role by reacting in DM to a bot message

Im trying to make a bot that send me a message with a reaction button, when I click it, give me a role in the server. Im trying to use on_raw_reaction_add event but I cant reach a solution to make it, Im always getting errors at getting guild roles and this stuff.
In this case, guild is none, I dont know what Im doing wrong.
My code:
#client.command()
async def test(ctx):
global member
global message__id
global channel_id
channel_id = (ctx.channel.id)
member = ctx.message.author
embed = discord.Embed(title="Verify your account", color=0x03fc14)
embed.add_field(name=f"Verification!", value=('React to this message to get verified!'), inline=False)
embed.set_footer(text=ctx.author, icon_url=ctx.author.avatar_url)
mesg = await member.send(embed=embed)
await mesg.add_reaction("✅")
message__id = mesg.id
print("EXECUTED")
#client.event
async def on_raw_reaction_add(payload):
print("reacted")
print("messageid accepted")
guild = client.get_guild(payload.guild_id)
if guild is not None:
print("messageid accepted")
reactor = payload.guild.get_member(payload.member.id)
role = discord.utils.get(guild.roles, name="Member")
if payload.emoji.name == '✅':
print("emoji accepted")
await reactor.add_roles(role)
EDIT:
I changed my on_raw_reaction_add event:
#client.event
async def on_raw_reaction_add(payload):
print("reacted")
print("messageid accepted")
guild = client.get_guild(payload.guild_id)
if guild is not None:
print("guild not none ")
reactor = payload.guild.get_member(payload.member.id)
role = discord.utils.get(guild.roles, name="Verified")
if payload.emoji.name == '✅':
print("emoji accepted")
await reactor.add_roles(role)
else:
print("guild none")
And this is what happen when I try the method:
First three words are the prints of the bot reacting his own message, the "EXECUTED" is the print of test method and the last three messages. are when I react the bot message
In this case, I suggest using a wait_for rather than on_raw_reaction_add.
Example, as seen in the docs:
#client.command(aliases=["t"])
async def test(ctx):
embed = discord.Embed(title="Verify your account", color=0x03fc14)
embed.add_field(name=f"Verification!", value=('React to this message to get verified!'), inline=False)
embed.set_footer(text=ctx.author, icon_url=ctx.author.avatar_url)
# sends message to command author
mesg = await ctx.author.send(embed=embed)
await mesg.add_reaction("✅")
#check if the reactor is the user and if that reaction is the check mark
def check(reaction, user):
return user == ctx.author and str(reaction.emoji) == '✅'
try:
#wait for the user to react according to the checks
reaction, user = await client.wait_for('reaction_add', timeout=60.0, check=check)
except asyncio.TimeoutError:
# 60 seconds without reaction
await ctx.send('Timed out')
else:
await ctx.send('✅')
docs- https://discordpy.readthedocs.io/en/stable/api.html?highlight=wait_for#discord.Client.wait_for
async def test(ctx):
global member
global message__id
global channel_id
channel_id = (ctx.channel.id)
member = ctx.message.author
embed = discord.Embed(title="Verify your account", color=0x03fc14)
embed.add_field(name=f"Verification!", value=('React to this message to get verified!'), inline=False)
embed.set_footer(text=ctx.author, icon_url=ctx.author.avatar_url)
mesg = await member.send(embed=embed)
await mesg.add_reaction("✅")
message__id = mesg.id
print("EXECUTED")
role = get(ctx.guild.roles, id=role id here)
done = False
while done == False:
reaction, user = await client.wait_for(“reaction_add”, check=check)
if user == client.user:
continue
await member.add_roles(role)
done = True
I am pretty sure something like this would work :D
When you do guild is not None, it will never fire because you are reacting in a DM channel context - where the guild is None. To access the guild information from the DM, you'll need to save it somewhere in the message (or save it yourself internally). Then, you have the guild object and you're able to add roles or do things to it.
#client.command()
async def testrole(ctx):
member = ctx.author
# ...
embed = discord.Embed(title="Verify your account", color=0x03fc14)
embed.add_field(name=f"Verification!", value=('React to this message to get verified!'), inline=False)
embed.set_footer(text=ctx.author, icon_url=ctx.author.avatar_url)
mesg = await member.send(str(ctx.guild.id), embed=embed) # we need the guild information somewhere
await mesg.add_reaction("✅")
#client.event
async def on_reaction_add(reaction, user): # there's really no need to use raw event here
if user.id == client.user.id:
return
if reaction.message.guild is None:
if reaction.emoji == '\u2705':
# we have to get the guild that we saved in the other function
# there is no other way to know the guild, since we're reacting in the DM
# that's why it was saved inside of the message that was sent to the user
guild_id = int(reaction.message.content)
guild = client.get_guild(guild_id)
member = guild.get_member(user.id)
await member.add_roles(...) # change this with your roles

Discord.py "message" is not defined error even though nothing is wrong?

So I am pretty new to making Discord bots and python, however, whenever I try to run this it returns an error:
Here is my code:
import os
import discord
from discord.ext import commands
import keepAlive
keepAlive.awake("https://Shulker.E1ytra.repl.co", False)
TOKEN = os.environ['TOKEN']
intents = discord.Intents().all()
bot = commands.Bot(command_prefix='?', intents=intents)
#bot.event
async def on_member_join(member):
guild = await bot.fetch_guild(958309214663622697)
role = discord.utils.get(guild.roles, name='unverified')
await member.add_roles(role)
await bot.process_commands(message)
#bot.command()
async def verf(ctx, arg):
if (arg == '51304'):
await ctx.message.delete()
member = ctx.author
role = discord.utils.get(ctx.guild.roles, name="Basement People")
await member.add_roles(role)
role = discord.utils.get(ctx.guild.roles, name="unverified")
await member.remove_roles(role)
embedVar = discord.Embed(title=" ", description=(ctx.message.author) + "Welcome to the server.", color=0x9b59b6)
await ctx.send(embed=embedVar, delete_after=5)
else:
await ctx.message.delete()
embedVar = discord.Embed(title=" ", description=(ctx.message.author) + "The secret code is invalid.", color=0x9b59b6)
await ctx.send(embed=embedVar, delete_after=5)
#bot.command()
#commands.has_permissions(kick_members=True)
async def kick(ctx, member: discord.Member, *, reason=None):
if reason == None:
reason = "N/A"
await ctx.message.delete()
await ctx.guild.kick(member)
embedVar = discord.Embed(title=" ", description=f"{member.mention} has been kicked. Reason: {reason}", color=0x9b59b6)
await ctx.send(embed=embedVar)
#bot.command()
#commands.has_permissions(ban_members=True)
async def ban(ctx, member: discord.Member, *, reason=None):
if reason == None:
reason = "N/A"
await ctx.message.delete()
await ctx.guild.ban(member)
embedVar = discord.Embed(title=" ", description=f"{member.mention} has been banned. Reason: {reason}", color=0x9b59b6)
await ctx.send(embed=embedVar)
#bot.command()
#commands.has_permissions(ban_members=True)
async def unban(ctx, member: discord.Member, *, reason=None):
if reason == None:
reason = "N/A"
await ctx.message.delete()
await ctx.guild.unban(member)
embedVar = discord.Embed(title=" ", description=f"{member.mention} has been unbanned. Reason: {reason}", color=0x9b59b6)
await ctx.send(embed=embedVar)
#bot.command()
#commands.has_permissions(manage_channels=True)
async def lock(ctx, channel : discord.TextChannel=None):
await ctx.message.delete()
overwrite = ctx.channel.overwrites_for(ctx.guild.default_role)
overwrite.send_messages = False
await ctx.channel.set_permissions(ctx.guild.default_role, overwrite=overwrite)
embedVar = discord.Embed(title=" ", description=f"<#{ctx.channel.id}> has been locked.", color=0x9b59b6)
await ctx.send(embed=embedVar)
#bot.command()
#commands.has_permissions(manage_channels=True)
async def unlock(ctx, channel : discord.TextChannel=None):
await ctx.message.delete()
overwrite = ctx.channel.overwrites_for(ctx.guild.default_role)
overwrite.send_messages = True
await ctx.channel.set_permissions(ctx.guild.default_role, overwrite=overwrite)
embedVar = discord.Embed(title=" ", description=f"<#{ctx.channel.id}> has been unlocked.", color=0x9b59b6)
await ctx.send(embed=embedVar)
bot.run(TOKEN)
It did run earlier and did perform actions without any errors but I don't know what's wrong in here. It's getting really confusing. I do not know what to assign to "message" to make it normal. Is this just Replit or something's wrong with my code?
Again, I am stupid, don't kill me in the comments.
When you do description=(ctx.message.author) + "Welcome to the server." python does not know how to get a string from the User (or Member) you get from the author field of message (docs).
What you probably want is ctx.message.author.mention which will give you a string that mentions the author or author.display_name.

Discord.py on_message event isn't processing any commands - Modmail Event

I'm creating a mod-mail feature which members can message the bot and it will respond with instructions. However the event works fine with the exception of bot commands. Here is my code. Strangely no errors were detected.
sent_users = []
modmail_channel = client.get_channel(910023874727542794)
#client.event
async def on_message(message):
if message.guild:
return
if message.author == client.user:
return
if message.author.id in sent_users:
return
embed = discord.Embed(color = color)
embed.set_author(name=f"Misaland Modmail System", icon_url=f'{message.author.avatar_url}')
embed.add_field(name='Report a Member: ', value=f"React with <:Wojak1:917122152078147615> if you would like to report a member.")
embed.add_field(name='Report a Staff Member:', value=f"React with <:grim1:925758467099222066> if you would like to report a staff.")
embed.add_field(name='Warn Appeal:', value=f"React with <:Lovecat:919055184125100102> if you would like to appeal a warning.")
embed.add_field(name='Question:', value=f"React with <:gasm:917112456776679575> if you have a question about the server")
embed.add_field(name='Leave a Review', value=f"React with <:surebuddy1:917122193287163924> to leave a review about the server")
embed.add_field(name='Server Invite', value=f'React with <:smirk:910565317363773511> to get the server invite.')
embed.set_footer(text='Any questions asked that isnt related to the list, you will be severely abused')
msg = await message.author.send(embed=embed)
await msg.add_reaction("<:Wojak1:917122152078147615>")
await msg.add_reaction("<:grim1:925758467099222066>")
await msg.add_reaction("<:Lovecat:919055184125100102>")
await msg.add_reaction("<:gasm:917112456776679575>")
await msg.add_reaction("<:surebuddy1:917122193287163924>")
await msg.add_reaction("<:smirk:910565317363773511>")
sent_users.append(message.author.id)
try:
def check(reaction, user):
return user == message.author and str(reaction.emoji) in ['<:Wojak1:917122152078147615>', '<:grim1:925758467099222066>','<:Lovecat:919055184125100102>','<:gasm:917112456776679575>','<:surebuddy1:917122193287163924>','<:smirk:910565317363773511>']
reaction, user = await client.wait_for("reaction_add", timeout=60, check=check)
if str(reaction.emoji) == "<:Wojak1:917122152078147615>":
embed = discord.Embed(color=color)
embed.set_author(name=f"Misaland Member Report", icon_url=f'{message.author.avatar_url}')
embed.add_field(name="How to Report:", value="Send the ID of the person you are reporting and attach a screenshot breaking the rules")
embed.set_footer(text="Misaland | Member Report")
await message.author.send(embed = embed)
message = await client.wait_for("message", timeout=60, check=lambda m: m.channel == message.channel and m.author == message.author)
embed = discord.Embed(title=f"{message.content}", color=color)
await modmail_channel.send(embed=embed)
except asyncio.TimeoutError:
await message.delete()
Try putting
await bot.process_commands(message)
at the end of your code in
async def on_message(message):
If you're using commands outside of on_message, it's overridden

Discord.py kick command not working (missing perms error)

I am currently working on a kick command that does a double check with the user before carrying out action for my discord bot, and came up with this:
#bot.command()
#commands.has_permissions(manage_guild=True)
async def kick(ctx,
member: discord.Member = None,
*,
reason="No reason provided"):
server_name = ctx.guild.name
user = member
if member == None:
await ctx.send(
f'{x_mark} **{ctx.message.author.name},** please mention somebody to kick.')
return
if member == ctx.message.author:
await ctx.send(
f'{x_mark} **{ctx.message.author.name},** you can\'t kick yourself, silly.')
return
embedcheck = discord.Embed(
title="Kick",
colour=0xFFD166,
description=f'Are you sure you want to kick **{user}?**')
embeddone = discord.Embed(
title="Kicked",
colour=0x06D6A0,
description=f'**{user}** has been kicked from the server.')
embedfail = discord.Embed(
title="Not Kicked",
colour=0xEF476F,
description=f'The kick did not carry out.')
msg = await ctx.send(embed=embedcheck)
await msg.add_reaction(check_mark)
await msg.add_reaction(x_mark)
def check(rctn, user):
return user.id == ctx.author.id and str(rctn) in [check_mark, x_mark]
while True:
try:
reaction, user = await bot.wait_for(
'reaction_add', timeout=60.0, check=check)
if str(reaction.emoji) == check_mark:
await msg.edit(embed=embeddone)
await user.kick(reason=reason)
if reason == None:
await user.send(
f'**{user.name}**, you were kicked from {server_name}. No reason was provided.'
)
else:
await user.send(
f'**{user.name}**, you were kicked from {server_name} for {reason}.'
)
return
elif str(reaction.emoji) == x_mark:
await msg.edit(embed=embedfail)
return
except asyncio.TimeoutError:
await msg.edit(embed=embedfail)
return
However when I do this, I get the error:
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: Forbidden: 403 Forbidden (error code: 50013): Missing Permissions
I have no clue why this is happening, as the bot has every permission checked, as do I, and I am the server owner. Any help would be appriciated, thank you.
Update: I found the error, when running the command it would try to kick the user of the command instead of the specified member. Here is my updated code:
#commands.command()
#commands.has_permissions(kick_members = True)
#commands.bot_has_permissions(kick_members = True)
async def kick(self, ctx, member: discord.Member, *, reason="No reason provided"):
server_name = ctx.guild.name
if member == ctx.message.author:
await ctx.send(
f'{x_mark} **{ctx.message.author.name},** you can\'t kick yourself, silly.')
return
embedcheck = discord.Embed(
title="Kick",
colour=0xFFD166,
description=f'Are you sure you want to kick **{member}?**')
embeddone = discord.Embed(
title="Kicked",
colour=0x06D6A0,
description=f'**{member}** has been kicked from the server.')
embedfail = discord.Embed(
title="Not Kicked",
colour=0xEF476F,
description=f'The kick did not carry out.')
msg = await ctx.send(embed=embedcheck)
await msg.add_reaction(check_mark)
await msg.add_reaction(x_mark)
def check(rctn, user):
return user.id == ctx.author.id and str(rctn) in [check_mark, x_mark]
while True:
try:
reaction, user = await self.bot.wait_for(
'reaction_add', timeout=60.0, check=check)
if str(reaction.emoji) == check_mark:
await msg.edit(embed=embeddone)
await member.kick(reason=reason)
await member.send(f'**{member.name}**, you were kicked from {server_name} for {reason}.')
return
elif str(reaction.emoji) == x_mark:
await msg.edit(embed=embedfail)
return
except asyncio.TimeoutError:
await msg.edit(embed=embedfail)
return
#kick.error
async def kick_error(self, ctx, error):
if isinstance(error, commands.MissingRequiredArgument):
await ctx.send(f'{x_mark} **{ctx.message.author.name}**, you need to mention someone to kick.')
elif isinstance(error, commands.BadArgument):
await ctx.send(f'{x_mark} **{ctx.message.author.name}**, I could not find a user with that name.')
else:
raise error
This issue is that you are checking for manage_guild which is not the correct permission. Also keep in mind you are mixing up bot and commands
#bot.command()
#bot.has_permissions(kick_user = True) # to check the user itself
#bot.bot_has_permissions(kick_user = True) # to check the bot
async def kick(ctx):
Remember to allow all intents like this
intents = discord.Intents().all()
bot = commands.Bot(command_prefix="$", intents=intents)

Categories