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