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 making discord music bot and use wavelink library.
I write this code:
#commands.Cog.listener()
async def on_wavelink_track_end(player: wavelink.Player, track: wavelink.Track):
ctx = player.ctx
vc: player = ctx.voice_client
if vc.loop:
return await vc.play(track)
next_song = vc.queue.get()
await vc.play(next_song)
await ctx.send(f"Сейчас играет {next_song.title}")
#commands.command()
async def play(self,ctx: commands.Context, *, search: wavelink.YouTubeTrack):
if not ctx.author.voice:
return await ctx.send("Ты не в голосовом канале!", delete_after = 10)
if not ctx.voice_client:
vc: wavelink.Player = await ctx.author.voice.channel.connect(cls = wavelink.Player)
else:
vc: wavelink.Player = ctx.voice_client
if vc.queue.is_empty and vc.is_playing:
await vc.play(search)
m = search.duration/60
await ctx.send(f"Сейчас играет `{search.title}` продолжительностью `{round(m, 2)}` минут")
else:
await vc.queue.put_wait(search)
await ctx.send(f"Добавлен {search.title} трек в очередь")
vc.ctx = ctx
setattr(vc, "loop", False)
And also I got this error
TypeError: Music.on_wavelink_track_end() got multiple values for argument 'track'
Another commands works properly, but play command do not append to wavelink queue and just play new song if we type play again.
Any ideas?
#commands.Cog.listener()
async def on_wavelink_track_end(player: wavelink.Player, track: wavelink.Track):
#You need to pass in `self` to here ⤴
So your code will look like this
#commands.Cog.listener()
async def on_wavelink_track_end(self, player: wavelink.Player, track: wavelink.Track):
ctx = player.ctx
vc: player = ctx.voice_client
if vc.loop:
return await vc.play(track)
next_song = vc.queue.get()
await vc.play(next_song)
await ctx.send(f"Сейчас играет {next_song.title}")
#commands.command()
async def play(self,ctx: commands.Context, *, search: wavelink.YouTubeTrack):
if not ctx.author.voice:
return await ctx.send("Ты не в голосовом канале!", delete_after = 10)
if not ctx.voice_client:
vc: wavelink.Player = await ctx.author.voice.channel.connect(cls = wavelink.Player)
else:
vc: wavelink.Player = ctx.voice_client
if vc.queue.is_empty and vc.is_playing:
await vc.play(search)
m = search.duration/60
await ctx.send(f"Сейчас играет `{search.title}` продолжительностью `{round(m, 2)}` минут")
else:
await vc.queue.put_wait(search)
await ctx.send(f"Добавлен {search.title} трек в очередь")
vc.ctx = ctx
setattr(vc, "loop", False)
This is probably it.
• Sxviaat
simply add self
async def on_wavelink_track_end(self , player: wavelink.Player, track: wavelink.Track)
I have tried to code a music bot of sorts, and it the code I put for the pause command doesn't work. I don't know about the resume command, since I'd have to first get the pause command working.
Here is the code:
#client.command(pass_context = True)
async def join(ctx):
if (ctx.author.voice):
vc = ctx.message.author.voice.channel
voice = await vc.connect()
source = FFmpegPCMAudio('Forest Battle - Battle music.mp3')
player = voice.play(source)
else:
await ctx.send("You need to be in a voice channel before using this command!")
#client.command(pass_context = True)
async def leave(ctx):
if (ctx.voice_client):
await ctx.guild.voice_client.disconnect()
await ctx.send("`RSS Dnd Bot has left the voice channel!`")
else:
await ctx.send("`RSS Dnd Bot isn't currently in any voice channel!`")
#client.command(pass_context = True)
async def pause(ctx):
voice = discord.utils.get(client.voice_clients, guild=ctx.guild)
if voice.is_playing():
voice.pause
else:
await ctx.send("`Nothing is currently playing right now!`")
#client.command(pass_context = True)
async def resume(ctx):
voice = discord.utils.get(client.voice_clients, guild=ctx.guild)
if voice.is_paused():
voice.resume()
else:
await ctx.send("`Nothing is currently paused right now!`")
This is my pause command:
#client.command(name='pause', description="pauses music")
async def pause_(ctx):
"""Pause the currently playing song."""
vc = ctx.voice_client
if not vc or not vc.is_playing():
embed = discord.Embed(title="", description="I am currently not playing anything", color=discord.Color.green())
return await ctx.send(embed=embed)
elif vc.is_paused():
return
vc.pause()
await ctx.send("Paused ⏸️")
This is my resume command:
#client.command(name='resume', description="resumes music")
async def resume_(ctx):
"""Resume the currently paused song."""
vc = ctx.voice_client
if not vc or not vc.is_connected():
embed = discord.Embed(title="", description="I'm not connected to a voice channel", color=discord.Color.green())
return await ctx.send(embed=embed)
elif not vc.is_paused():
return
vc.resume()
await ctx.send("Resuming ⏯️")
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.
I kinda made this working music bot code, it join vc and play the song. But when its in voice it wont play another one, i need to disconnect him. I want that he play next song even if he is joined. How to do it?
code(part where i want the thing):
#bot.command()
async def hraj(ctx, url):
if not ctx.message.author.voice:
await ctx.send("Musíš být ve voicu ty pepego!")
return
else:
channel = ctx.message.author.voice.channel
await channel.connect()
server = ctx.message.guild
voice_channel = server.voice_client
async with ctx.typing():
player = await YTDLSource.from_url(url, loop=bot.loop)
voice_channel.play(player, after=lambda e: print("Error. %s" %e if e else None))
e = discord.Embed(title="Právě hraje:", description=f"[{player.title}]({url})", color=0x0091ff)
e.set_footer(text="Lets go jdem vibovat <333")
await ctx.send(embed=e)
You could use
voice = discord.utils.get(client.voice_clients, guild=ctx.guild)
if voice == None:
channel = ctx.message.author.voice.channel
This works because discord.utils.get(client.voice_clients, guild=ctx.guild) returns None if your bot isn't in a voice channel.
So your code would be:
#bot.command()
async def hraj(ctx, url):
voice = discord.utils.get(client.voice_clients, guild=ctx.guild)
if voice == None:
channel = ctx.message.author.voice.channel
else:
await ctx.send('Musíš být ve voicu' ty pepego)
await channel.connect()
server = ctx.message.guild
voice_channel = server.voice_client
async with ctx.typing():
player = await YTDLSource.from_url(url, loop=bot.loop)
voice_channel.play(player, after=lambda e: print("Error. %s" %e if e else None))
e = discord.Embed(title="Právě hraje:", description=f"[{player.title}]({url})", color=0x0091ff)
e.set_footer(text="Lets go jdem vibovat <333")
await ctx.send(embed=e)
Your question wasn't very clear btw.