#discord-bots
1 messages ยท Page 196 of 1
They're in Python repl
im very new to coding
yeah and then dont forget to client.run("YOURTOKEN") in your code
okay 2 secs
still getting invalid syntax
show the code? you can delete the token
Hey @slate swan! I noticed you posted a seemingly valid Discord API token in your message and have removed your message. This means that your token has been compromised. Please change your token immediately at: https://discord.com/developers/applications
Feel free to re-post it with the token removed. If you believe this was a mistake, please let us know!
bruh
!code
Here's how to format Python code on Discord:
```py
print('Hello world!')
```
These are backticks, not quotes. Check this out if you can't find the backtick key.
Pasting large amounts of code
If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
well, your code isnt large, so you could just paste it as a code block
I just said you're in the Python repl
import discord
from discord.ext import commands
client = commands.bot(command_prefix="=", intents=discord.Intents.all())
@client.event
async def on_ready():
print("Success bot it ready")
client.run("")
seems like you are still in the repl, yep
Exit it before running
i guess you need capital B instead of b
where?
commands.Bot
Bot
๐
You just sent your token
Nice
Is this code correct?
if len(current_players) == 10 and after.member not in current_players:
if after.member not in queue:
queue.append(after.member)
await after.member.disconnect()
else:
current_players.append(after.member)```
Should I use else: or add member to current players if current players is less then 10 and member is not in current players list
= 10 is safer
if member == None:
em1=nextcord.Embed(title=" Error", description=f" Please mention a member!", color=nextcord.Color.red())
await ctx.send(embed=em1)
return
elif time == None:
em2=nextcord.Embed(title=" Error", description=f" Please set the time!", color=nextcord.Color.red())
await ctx.send(embed=em2)
time=convert(time)
return
elif member == ctx.author:
em3=nextcord.Embed(title=" Error", description=f" You can't mute yourself!", color=nextcord.Color.red())
await ctx.send(embed=em3)
return
elif muterole == None:
await ctx.send("No muterole has been setup for this server!")
return
elif muterole in member.roles:
embed=nextcord.Embed(title=" Error", description=f" This member is already muted!", color=nextcord.Color.red())
await ctx.send(embed=embed)
else:```
``` File "c:\Users\PC\Desktop\HelpMe Bot\main.py", line 121, in mute
elif muterole == None:
UnboundLocalError: local variable 'muterole' referenced before assignment```
know what the error means
if len(current_players) >= 10 and member not in current_players:
if member not in queue:
queue.append(member)
await member.move_to(None)
elif member not in current_players:
current_players.append(member)```
but like thats weird i didnt understand
What do you think about this code?
This will add a player to current players even if max amount is hit
So what is your solution?
muterole is undefined at the moment of usage in if statement
if member in current_players:
return
if len(current_players) >= 10:
await member.disconnect()
return
current_players.append(member)```
i did defined i t so why does it happen
how do i fix it
Could you show full code
yeah
You probably defined it in some if block that is not necessarily executed
@bot.command()
@commands.has_permissions(administrator=True)
async def muterole(ctx, role_: nextcord.Role = None):
if role_ ==None:
await ctx.send("Mention a role!")
else:
async with aiosqlite.connect("main.db") as db:
async with db.cursor() as cursor:
await cursor.execute('SELECT role_id FROM mute WHERE guild = ?', (ctx.guild.id,))
role = await cursor.fetchone()
if role:
await cursor.execute('UPDATE mute SET role_id = ? WHERE guild = ?', (role_.id, ctx.guild.id,))
else:
await cursor.execute('INSERT INTO mute (role_id, guild) VALUES (?, ?)', (role_.id, ctx.guild.id,))
await ctx.send(f"Successfuly set the mute role to - {role_.mention}")
await db.commit()
def convert(time):
pos = ["s", "m", "h", "d"]
time_dict = {"s" : 1, "m" : 60, "h" : 3600, "d": 86400}
unit = time[-1]
if unit not in pos:
return -1
try:
val = int(time[:-1])
except:
return -2
return val * time_dict[unit]
@bot.command()
@commands.has_permissions(manage_messages=True)
async def mute(ctx, member: nextcord.Member = None, time: convert = None, *, reason=None):
async with aiosqlite.connect("main.db") as db:
async with db.cursor() as cursor:
await cursor.execute('SELECT role_id FROM mute WHERE guild = ? AND time = ?', (ctx.guild.id, time,))
role_id = await cursor.fetchone()
if role_id:
muterole = ctx.guild.get_role(role_id)
if member == None:
em1=nextcord.Embed(title=" Error", description=f" Please mention a member!", color=nextcord.Color.red())
await ctx.send(embed=em1)
return
elif time == None:
em2=nextcord.Embed(title=" Error", description=f" Please set the time!", color=nextcord.Color.red())
await ctx.send(embed=em2)
time=convert(time)
return
elif member == ctx.author:
em3=nextcord.Embed(title=" Error", description=f" You can't mute yourself!", color=nextcord.Color.red())
await ctx.send(embed=em3)
return
elif muterole == None:
await ctx.send("No muterole has been setup for this server!")
return
elif muterole in member.roles:
embed=nextcord.Embed(title=" Error", description=f" This member is already muted!", color=nextcord.Color.red())
await ctx.send(embed=embed)
else:
await member.add_roles(muterole)
emmu = nextcord.Embed(
color=nextcord.Colour.green(),
title=' Muted Success')
emmu.add_field(name=f"__**Moderation:**__", value=ctx.author.mention, inline = False)
emmu.add_field(name=f"__**Member:**__", value=member, inline = False)
emmu.add_field(name=f"__**Time:**__", value=time, inline = False)
emmu.add_field(name=f"__**Reason:**__", value=reason, inline = False)
emmu.set_footer(text=f'Muted by {ctx.author}')
await ctx.send(embed=emmu)
await member.remove_roles(time=time)```
Yeah
wdymn
If role_id is None, muterole will never be assigned
You need to ensure it is always defined, for example you can add muterole = None before making a query
ohhhh
as a paramter?
And yeah you should have one db connection for bot
Creating a connection is expensive and you can just use one for everything
As a variable
The way you added it here will make it so it is always None lol
if muterole = None
....
And still will be undefined if role_id is none
I mean it should be like py muterole = None role_id = await query(...) # pseudo if role_id is not None: muterole = get_role(role_id)
is: if role_id != None: better?
No
oh
Comparisons to None and bools should be done with is keyword
oh okay
For pure bool it's just if obj and if not obj, for bool | None it's is too
For None it's always is
tysmmmm
Would this work to add them to the queue as well?
if member in current_players:
return
if len(current_players) >= 10:
await member.disconnect()
if member not in queue:
queue.append(member)
return
current_players.append(member)```
Hey @tired notch!
You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.
i am getting this error while trying to run discord.py, was working fine last night
What's the proper means to invite or remove users from Stage? I see request_to_speak but not immediately obvious how to use it since it has no args so I'm not entirely sure on how to implement, any info/examples would be great ๐ I'm using Disnake btw
how do i make a global app command check?
and also can a followup be a normal message if the interaction was deffered ephemerally?
@bot.command()
@commands.has_permissions(manage_messages=True)
async def mute(ctx, member: nextcord.Member = None, time: convert = None, *, reason=None):
async with aiosqlite.connect("main.db") as db:
async with db.cursor() as cursor:
await cursor.execute('SELECT role_id FROM mute WHERE guild = ? AND time = ?', (ctx.guild.id, time,))
role_id = await cursor.fetchone()
if role_id:
muterole = ctx.guild.get_role(role_id)
muterole = None
if role_id is not None:
muterole = ctx.guild.get_role(role_id)
if member == None:
em1=nextcord.Embed(title=" Error", description=f" Please mention a member!", color=nextcord.Color.red())
await ctx.send(embed=em1)
return
elif time == None:
em2=nextcord.Embed(title=" Error", description=f" Please set the time!", color=nextcord.Color.red())
await ctx.send(embed=em2)
time=convert(time)
return
elif member == ctx.author:
em3=nextcord.Embed(title=" Error", description=f" You can't mute yourself!", color=nextcord.Color.red())
await ctx.send(embed=em3)
return
elif muterole == None:
await ctx.send("No muterole has been setup for this server!")
return
elif muterole in member.roles:
embed=nextcord.Embed(title=" Error", description=f" This member is already muted!", color=nextcord.Color.red())
await ctx.send(embed=embed)
else:
await member.add_roles(muterole)
emmu = nextcord.Embed(
color=nextcord.Colour.green(),
title=' Muted Success')
emmu.add_field(name=f"__**Moderation:**__", value=ctx.author.mention, inline = False)
emmu.add_field(name=f"__**Member:**__", value=member, inline = False)
emmu.add_field(name=f"__**Time:**__", value=time, inline = False)
emmu.add_field(name=f"__**Reason:**__", value=reason, inline = False)
emmu.set_footer(text=f'Muted by {ctx.author}')
await ctx.send(embed=emmu)
await member.remove_roles(time=time)
still the same error
elif muterole == None:
UnboundLocalError: local variable 'muterole' referenced before assignment```
if role_id:
muterole = ctx.guild.get_role(role_id)
muterole = None
if role_id is not None:
muterole = ctx.guild.get_role(role_id)
i remember you
install python certificates
oh hey mudkip! lol
Hey, @smoky sinew I was thinking about the code last night, and instead of the second pull, do i need to chance that to a slash>
mb i'm about to go out
you're good. Just tryin to think about why commands aren't appearing lol
I made a help page too so I may get someone there
why are icons not showing
hey, anyone know mongo things ?
prob just type it again or smt
I remember you as well! Hope all is well mudkip ๐
File "c:\Users\ovis\OneDrive\Desktop\Discord-Economy-Bot-main\Discord-Economy-Bot-main\Systems\Economy.py", line 21, in <module>
with open("Configs/config.yml", "r", encoding="utf-8") as file: any idea ?
what lol
that's not even like 1/3 of the error
Relatable
@smoky sinewfound out what's was wrong
hello , i'm trying to get my bot online , but everytime i run the code , nothing happens , no errors and the bot isn't online , if anyone has any idea on what to do that'd be great!
share your code
` import discord
import responses
send messages
async def send_message(message, user_message, is_private):
try:
reponse = responses.handle_response(user_message)
await message.author.send(response) if is_private else await message.channel.send(response)
except Exception as e:
print(e)
def run_discord_bot():
TOKEN = 'token'
intents = discord.Intents.default()
intents.message_content = True
client = discord.Client(intents=intents)
@client.event
async def on_ready():
print(f'{client.user} is now running!')
@client.event
async def on_message(message):
if message.author == client.user:
return
username = str(message.author)
user_message = str(message.content)
channel = str(message.channel)
print(f'{username} said: "{user_message}" ({channel})')
if user_message[0] == '?':
user_message = user_message[1:]
await send_message(message, user_message, is_private=True)
else:
await send_message(message, user_message, is_private=False)
client.run(TOKEN)
`
!code
Here's how to format Python code on Discord:
```py
print('Hello world!')
```
These are backticks, not quotes. Check this out if you can't find the backtick key.
well you're not even running the discord bot function
but it wouldn't work anyway since you can't do async stuff inside an synchronous function
i did that in another .py file
`import bot
if name == 'main':
bot.run_discord_bot()
`
read this
import bot
if __name__ == '__main__':
bot.run_discord_bot()
can u explain further more
i followed a tuto
Why would you even create a function to setup the instances
@naive briar this is why
don't follow tutorials
do u mean the run discord bot function?
send_message is already async
You didn't even run the bot to begin with
he help channels don't last very long do they? lol
I am looking for a way to give a role after a reaction, but they first have to enter a gamertag or PSN (This doesn't have to be verified, just something entered into the field). This is what I have so far, but there are no commands appearing when the bot goes live and I don't know where to go from here. Eventually I want a database to hold all of the information as well.
Thats what I have so far
Mudkip was helping me but I fear im stressing him out lol
30 minutes
try this maybe:
@commands.is_owner()
@client.command()
async def sync(ctx):
await client.tree.sync()
They still didn't add the command to the bot instance
Thats what I thought when I was looking at it lol
But im fairly new so I wasn't entirely sure
didn't know you need to do that
i thought the decorator took care of that
so bot.add_command i guess?
Or
@bot.event
async def on_ready():
print(f'{bot.user.name}')
print(f'{bot.user.id}')
print("Online")
print("-------------")
await bot.tree.sync()
bot.add_view(MyModal())
@bot.tree.command()
Does
ah i see
This does not
...
Don't sync in on_ready
replace app_commands.command with client.tree.command i guess then
In my time as Helper, I see people syncing their CommandTree in the on_ready_event or in the new setup_hook entrypoint method. I do not advise this personally, it can lead to footguns if you aren't prepared. For examples, if you sync your tree before you load your extensions (which have your application commands), then you're effectively syncing an empty tree to Discord, which will wipe your commands. If you sync your tree and then make changes, you rely on the autosync and forget to sync changes, resulting in errors and failing commands.
@regal galleon
just make a message command to sync
Got discord bot source code from github, trying to run it but getting errors, everything look's fine but dont get it
raise CommandNotFound(name, parents)
discord.app_commands.errors.CommandNotFound: Application command 'balance' not found
Okay this is the best way
** @commands.command(aliases=['bal', 'money', 'profile'])
async def balance(self, ctx, member: discord.Member = None):
if member is None:
**```
the code you provided looks to be a message command, not an app command
So where to find a solution
run the message command instead of the application command?
Something is wrong, prefix is ! , but message command can run with /
discord.ext.commands.errors.CommandNotFound: Command "balance" is not found getting this then
is the cog loaded
with / show's everything whats loaded i think so
and getting this c:\ekonomika\main.py:83: RuntimeWarning: coroutine 'BotBase.load_extension' was never awaited
client.load_extension(f"Commands.{fn[:-3]}")
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
c:\ekonomika\main.py:87: RuntimeWarning: coroutine 'BotBase.load_extension' was never awaited
client.load_extension(f"Systems.Economy")
logging.info("------------- Loading -------------")
for fn in listdir("Commands"):
if fn.endswith(".py"):
logging.info(f"Loading: {fn}")
client.load_extension(f"Commands.{fn[:-3]}")
logging.info(f"Loaded {fn}")
logging.info(f"Loading: Economy System")
client.load_extension(f"Systems.Economy")
logging.info(f"Loaded Economy System")
logging.info("------------- Finished Loading -------------")
you're running a kind of outdated bot
github
so basically i need change alot
TypeError: Command.error() missing 1 required positional argument: 'coro'
the error poped up after pasted the kick.error command
purge.error command is running without problem
This is what I got so far, commands still aren't showing up
write bot instead client, i've never seen the client codes works so far
it pops up the error
as i observed
I have no error running the bot itself, the commands just don't show up
Do you know what decorators are
nope
as I said im pretty new lol
mudkip has been walking me through it the best he can lol
if you think of a fix please dm me ๐ I have to head out for a bit but I would love to communicate about what you think would help!
()
@client.tree.command()
with the @
if anyone can help im trying to make a bot that reacts with an emoji to a specific user after i say something like "!nerd (user) and then itll wait for them to send a message and react with the emoji ive choosed, ive got most of the code down but i have no idea how to make it wait for the specific user to send the message, and it just reacts to the message i send
does anyone have a unban codes for discord.py
is there any way to gen keys in discord.py using keyauth?
await member.remove_roles(time=time)
TypeError: remove_roles() got an unexpected keyword argument 'time'```
```py
await member.add_roles(muterole)
emmu = nextcord.Embed(
color=nextcord.Colour.green(),
title=' Muted Success')
emmu.add_field(name=f"__**Moderation:**__", value=ctx.author.mention, inline = False)
emmu.add_field(name=f"__**Member:**__", value=member, inline = False)
emmu.add_field(name=f"__**Time:**__", value=time, inline = False)
emmu.add_field(name=f"__**Reason:**__", value=reason, inline = False)
emmu.set_footer(text=f'Muted by {ctx.author}')
await ctx.send(embed=emmu)
await member.remove_roles(muterole,time=time)```
time doesn't exist...
you can't just make up an argument
!d discord.Member.remove_roles
await remove_roles(*roles, reason=None, atomic=True)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Removes [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role "discord.Role")s from this member.
You must have [`manage_roles`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_roles "discord.Permissions.manage_roles") to use this, and the removed [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role "discord.Role")s must appear lower in the list of roles than the highest role of the member.
i defined it
defined what
Wdym how
how did you define it
time: convert = None
? show the code
Do you guys know what the deal with Stages is atm? Is it something Discord will continue to be developing? I saw on a larger server they had a Stage with Video and a Chat Channel, are those features which we can confidently expect to be made available? I'm not sure if that's somehow functionality limited to boosted servers or something, just want more info on them so I can better understand what to expect in terms of the continued development and implementation of the feature
why my function is not detected by the code?
async def roll(self, ctx, args, aliases = ['r', 'diceroll', 'dice_roll', 'dice']):
not_failure = True
try:
indice = []
cont = 0
for indz in args:
if indz == "+" or indz == "-" or indz == "*" or indz == "/":
indice.append([cont,cont+1], indz)
cont = cont+1
args_result = args.split('+', '-', "*", "/")
total = 0
ind = 0
for y in args_result:
if "#" in y:
ind = ind + 1
if y != args_result[0]:
not_failure = False
break
if ind > 1:
break
if not_failure:
store = []
if "#" in args_result[0]:
mark = args_result.split('#')
args_result[0] = mark[1]
mark.pop(1)
for z in range(0, mark):
resp_sub = f"{z}#"
for x in args_result:
resp_sub = + f"{indice} {args_result[x]} {sub_roll(args_result[x])}"
resp_sub = + "\n"
else:
for x in args_result:
resp_sub = + f"{indice} {args_result[x]} {sub_roll(args_result[x])}"
store.append(sub_roll(args_result[x]))
sub_total = 0
for count, clock in enumerate(indice):
if clock == "*":
pos1 = indice[count][0]
pos2 = indice[count][1]
sub_total = sub_total + store[pos1] * store[pos2]
for ntz in range (count,store):
indice[ntz][0] = indice[ntz][0]-1
indice[ntz][1] = indice[ntz][1]-1
indice.pop(count)
store.remove(indice[count][0], ```
for count, clock in enumerate(indice):
if clock == "/":
pos1 = indice[count][0]
pos2 = indice[count][1]
sub_total = sub_total + store[pos1] / store[pos2]
for ntz in range (count,store):
indice[ntz][0] = indice[ntz][0]-1
indice[ntz][1] = indice[ntz][1]-1
indice.pop(count)
store.remove(indice[count][0], indice[count][1])
for clock in indice:
if clock == "+":
pos1 = indice[count][0]
pos2 = indice[count][1]
sub_total = sub_total + store[pos1] + store[pos2]
indice.pop(count)
store.remove(indice[count][0], indice[count][1])
if clock == "-":
pos1 = indice[count][0]
pos2 = indice[count][1]
sub_total = sub_total + store[pos1] - store[pos2]
indice.pop(count)
store.remove(indice[count][0], indice[count][1])
total = sub_total
resp_total = resp_sub + f"\n{total}"
except:
not_failure = False
if not_failure:
await ctx.send(resp_total)
else:
await ctx.send("Error! Arguments invalid")
.remove_roles doesn't take in time
this is my function:
result = []
total = 0
meta = []
if "d" in inp:
res = inp.split('d')
sub_r = []
z = 0
while(z < res[0]-1):
if res[1] == "f" or res[1] == "F":
sub_r.append(random.randint(1, 6))
if sub_r == range (1, 2):
sub_r[z] = "-"
elif sub_r == range (3,4):
sub_r[z] == "0"
else:
sub_r[z] == "+"
else:
sub_r.append(random.randint(1, res[1]))
z = z+1
result = sub_r
for x in result:
total = total+x
meta.append(result, total)
return meta```
And in which file do you have it
Hey @slate swan!
You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.
So it's inside a class?
yes
Then do self.sub_roll
oh i see
Whenever you wanna use a function you made inside the same class as the command add a self. in front of it
why my code is not working?
isntead of run the code it just says arguments invalid
guess it's because i need to convert string to number
@commands.command()
async def roll(self, ctx, args, aliases = ['r', 'diceroll', 'dice_roll', 'dice']):
not_failure = True
try:
indice = []
cont = 0
for indz in args:
if indz == "+" or indz == "-" or indz == "*" or indz == "/":
indice.append([cont,cont+1], indz)
cont = cont+1
args_result = args.split("+", "-", "*", "/")
total = 0
for y in args_result:
ind = 0
if "#" in y:
ind = ind + 1
if y != args_result[0]:
not_failure = False
break
if ind > 1:
break
if not_failure:
store = []
if "#" in args_result[0]:
mark = args_result.split('#')
args_result[0] = mark[1]
mark.pop(1)
for z in range(0, mark):
resp_sub = f"{z}#"
roll_result = self.sub_roll(args_result[x])
for x in args_result:
resp_sub = + f"{indice} {args_result[x]} {roll_result}"
store.append(roll_result[1])
resp_sub = + "\n"
else:
for x in args_result:
roll_result = self.sub_roll(args_result[x])
resp_sub = + f"{indice} {args_result[x]} {roll_result}"
store.append(roll_result[1])
sub_total = 0
for count, clock in enumerate(indice):
if clock == "*":
pos1 = indice[count][0]
pos2 = indice[count][1]
sub_total = sub_total + store[pos1] * store[pos2]
for ntz in range (count,store):
indice[ntz][0] = indice[ntz][0]-1
indice[ntz][1] = indice[ntz][1]-1
indice.pop(count)
store.remove(indice[count][0], indice[count][1])
for count, clock in enumerate(indice):
if clock == "/":
pos1 = indice[count][0]
pos2 = indice[count][1]
sub_total = sub_total + store[pos1] / store[pos2]
for ntz in range (count,store):
indice[ntz][0] = indice[ntz][0]-1
indice[ntz][1] = indice[ntz][1]-1
indice.pop(count)
store.remove(indice[count][0], indice[count][1])
for clock in indice:
if clock == "+":
pos1 = indice[count][0]
pos2 = indice[count][1]
sub_total = sub_total + store[pos1] + store[pos2]
indice.pop(count)
store.remove(indice[count][0], indice[count][1])
if clock == "-":
pos1 = indice[count][0]
pos2 = indice[count][1]
sub_total = sub_total + store[pos1] - store[pos2]
indice.pop(count)
store.remove(indice[count][0], indice[count][1])
total = sub_total
resp_total = resp_sub + f"\n{total}"
except:
not_failure = False
if not_failure:
await ctx.send(resp_total)
else:
await ctx.send("Error! Arguments invalid")
why it's just sending me a error message?
guess i need to provide more information
but how i do it?
discord.sinks.WaveSink() - module 'discord' has no attribute 'sinks' Hi, how to make it grate?
async def listen(ctx):
if ctx.voice_client:
ctx.voice_client.start_recording(discord.sinks.WaveSink(), callback, ctx)
await ctx.send("listening...")
else:
await ctx.send("not in a voice channel!")
async def callback(sink: discord.sinks, ctx):
for user_id, audio in sink.audio_data.items():
if user_id == ctx.author.id:
audio: discord.sinks.core.AudioData = audio
print(user_id)
filename = "audio.wav"
with open(filename, "wb") as f:
f.write(audio.file.getvalue())
text = model.transcribe(filename)["text"]
os.remove(filename)
print(f"Received from {ctx.author.name}: {text}")
reply = parse(text)
print(f"Reply: {reply}")
tts(ctx, reply)
# stops recording
@client.command()
async def stop(ctx):
ctx.voice_client.stop_recording()
``` How write this on nextcord? thanks
you don't need multiple
also why are your classes lowercase
Idk
fix them
But I kinda do because i have cooldown and etc
that can all be done in one error handler
How?
by checking the type of error
But isnโt the instance function can only have less than 2 args?
yes??
Help on built-in function isinstance in module builtins:
isinstance(obj, class_or_tuple, /)
Return whether an object is an instance of a class or of a subclass thereof.
A tuple, as in ``isinstance(x, (A, B, ...))``, may be given as the target to
check against. This is equivalent to ``isinstance(x, A) or isinstance(x, B)
or ...`` etc.
look at what the third part says
isinstance(object, classinfo)```
Return `True` if the *object* argument is an instance of the *classinfo* argument, or of a (direct, indirect, or [virtual](https://docs.python.org/3/glossary.html#term-abstract-base-class)) subclass thereof. If *object* is not an object of the given type, the function always returns `False`. If *classinfo* is a tuple of type objects (or recursively, other such tuples) or a [Union Type](https://docs.python.org/3/library/stdtypes.html#types-union) of multiple types, return `True` if *object* is an instance of any of the types. If *classinfo* is not a type or tuple of types and such tuples, a [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError "TypeError") exception is raised. [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError "TypeError") may not be raised for an invalid type if an earlier check succeeds.
Changed in version 3.10: *classinfo* can be a [Union Type](https://docs.python.org/3/library/stdtypes.html#types-union).
yeah nvm
do you have an error handler
im getting intent errors and im at a lose on how to fix them
import os
import requests
import discord
from discord.ext import commands
from discord_webhook import DiscordWebhook
intents = discord.Intents.default()
intents.guild_messages = True
intents = discord.Intents.default()
intents.privileged_intents = discord.Intents.privileged
client = commands.Bot(command_prefix='!', intents=intents)
@client.event
async def on_ready():
print(f'Bot is ready. Logged in as {client.user}')
not complete source... i know its an easy fix but i have brain fog atm ahha
remove the second intents defination
so
intents = discord.Intents.default()
intents.privileged_intents = discord.Intents.privileged
yea remove that
just a sidenote, you don't need the discord_webhook library, discord.py has full webhooks support
remove both of those lines....
now you remove all 4 lines bruh
remove only this.
How to send a message to a specific channel by its ID using slash command?
change .guild_messages to .message_content
!d discord.Client.get_partial_messageable
get_partial_messageable(id, *, guild_id=None, type=None)```
Returns a partial messageable with the given channel ID.
This is useful if you have a channel\_id but donโt want to do an API call to send messages to it.
New in version 2.0.
!d discord.abc.Messageable.send
await send(content=None, *, tts=False, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, ...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Sends a message to the destination with the content given.
The content must be a type that can convert to a string through `str(content)`. If the content is set to `None` (the default), then the `embed` parameter must be provided.
To upload a single file, the `file` parameter should be used with a single [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File "discord.File") object. To upload multiple files, the `files` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.11)") of [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File "discord.File") objects. **Specifying both parameters will lead to an exception**.
To upload a single embed, the `embed` parameter should be used with a single [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed "discord.Embed") object. To upload multiple embeds, the `embeds` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.11)") of [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed "discord.Embed") objects. **Specifying both parameters will lead to an exception**.
thank you โค๏ธ
@bot.tree.error
async def on_app_command_error(error: app_commands.AppCommandError, interaction: discord.Interaction):
if isinstance(error,app_commands.CommandOnCooldown):
await interaction.response.send_message(f"You are on a cooldown, Try again in {error.retry_after} seconds!",ephemeral=True)
else: raise error``` the cooldown works but it doesn't send the custom error msg, just "the app did not respond"
does anyone knows how to make a /say command
that only allows some users to use it
aka the bot owner
its discord.errors.CommandOnCooldown
the same as default error for message commands
@commands.owner_only() maybe
make it role specific or add some check
๐คจ there's nothing like errors.CommandOnCooldown what ur smoking asher
are whatever it is discord.Command then
it's just the wrong argument order
its morning i am still not awake
interaction comes before error
hm
go work on ur task bro
... u got good only no 1st mains take a break
@app_commands.is_owner()
@app_commands.describe(message = "The message to say.")
@app_commands.command()
async def say(self, interaction: discord.Interaction, message: str):
await interaction.response.send_message(message)
..yes it's a slash command, cope lol
if you want a message command the syntax is similar though
oh and also how do u make command only works for specific users
It's already in the code
At least try to understand the code, not just copy and paste
it already does
it only works for the bot owner
yes i mean like only person A and person B can use it not just the bot owner, also sorry if im just asking too much questions i forgot how to code
oh then how will it know when to remove the role?
what functionality are you trying to achieve?
like trying to make the role removed after the time is up
you'll have to handle this yourself
asycio.tasks()?
but you can do something like a "future task", utilizing the tasks functionality in dpy
example from a tag in discord.py server:
@tasks.loop()
async def yourtask():
# if you don't care about keeping records of old tasks, remove this WHERE and change the UPDATE to DELETE
next_task = await db_conn.fetchrow('SELECT * FROM tasks WHERE NOT completed ORDER BY end_time LIMIT 1')
# if no remaining tasks, stop the loop
if next_task is None:
yourtask.stop()
# sleep until the task should be done
await discord.utils.sleep_until(next_task['end_time'])
# do your task stuff here with `next_task`
# UPDATE the task to mark it completed, or DELETE it
await db_conn.execute('UPDATE tasks SET completed = true WHERE row_id = $1', next_task['row_id'])
# add a `before_loop` and `wait_until_ready` if you need the bot to be logged in
yourtask.start()
# in a command that adds new task in db
if yourtask.is_running():
yourtask.restart()
else:
yourtask.start()
assuming when the "time is up" is a datetime you would check against
something simliar may work
Thank you so much!!! Ill try
Well actually more easiest method is check if there is any column which rn lower than current time in timestamp if not return if yes delete the column from table and do the tasks
How do I make the bot mention the channel in the embed? This is my code.
@bot.event
async def on_message_edit(message_before, message_after):
channel = bot.get_channel(1063026363084316703)
editlogEmbed = discord.Embed(title="", description="", color=0xFF5349)
editlogEmbed.add_field(name="", value=f'A message sent by {message_before.author.mention} was edited in {message_before.channel}', inline=True)
editlogEmbed.add_field(name="Before:", value=f'{message_before.content}', inline=False)
editlogEmbed.add_field(name="After:", value=f'{message_after.content}', inline=False)
editlogEmbed.set_footer(text=f'Message ID: {message_before.id} โข Made by justin;#6868')
editlogEmbed.set_author(name=f'{message_before.author}', icon_url = f'{message_before.author.display_avatar}')
await channel.send(embed=editlogEmbed)```
channel.mention
I thought I tried that- Anyways, thanks.
msg = await interaction.followup.send(embed=embed)
thread = await msg.create_thread(name="Response Thread", auto_archive_duration=120)
I'm getting an error: This message does not have guild info attached.
Idk what's wrong here
Np!
the message might be in a DM channel
No it's a guild msg
can you print msg.guild?
Wait let me try
how would i make a number go up by +1 every time the command is run
hmm i see
is it because the message is a followup message -> webhook
hmm, iirc WebhookMessage should have the channel at least instead of a PartialMessageable
Just create the thread from the channel that is from the interaction
Why does it have to be from a message
I've tried using interaction.message.create_thread
pretty much a shortcut i suppose, also, i guess it is indeed in a DM channel there
lol why'd I lie
'NoneType' object has no attribute 'create_thread'
The channel the interaction was sent from.
Note that due to a Discord limitation, DM channels are not resolved since there is no data to complete them. These are PartialMessageable instead.
What even is interaction.message 
Never seen it before
maybe user's message I suppose
well, im not saying you're lying, im thinking your assumption on the intended behavior is incorrect
whats your full code other than this
it's just a chatgpt code, if the message length is exceeded then I'm splitting the message into thread
Not again
interaction.message wouldnt be filled by slash invoke btw
await send(content=..., *, username=..., avatar_url=..., tts=False, ephemeral=False, file=..., files=..., embed=..., embeds=..., allowed_mentions=..., view=..., thread=..., ...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Sends a message using the webhook.
The content must be a type that can convert to a string through `str(content)`.
To upload a single file, the `file` parameter should be used with a single [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File "discord.File") object.
If the `embed` parameter is provided, it must be of type [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed "discord.Embed") and it must be a rich embed type. You cannot mix the `embed` parameter with the `embeds` parameter, which must be a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.11)") of [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed "discord.Embed") objects to send.
Changed in version 2.0: This function will now raise [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError "(in Python v3.11)") instead of `InvalidArgument`.
okay
still getting this ValueError
This message does not have guild info attached.
Idk interaction.user just works fine but interaction.message is None
No
then what
What?
if not server members intent then what?
!d discord.Intents.guilds
Whether guild related events are enabled.
This corresponds to the following events...
I said what I said
I've discord.Intents.default() so it is enabled by default
A factory method that creates a Intents with everything enabled except presences, members, and message_content.
I've a /serverinfo command that works just fine
guys
i have the guild id i tried to get the guildwith get_guildbut it returns Nonetype and fetch_guild returns coroutine
it seems like WebhookMessage has an issue when resolving channels, you may wanna use interaction.channel.create_thread w/ message kwargs set to your msg webhook, ```py
msg = await interaction.followup.send(embed=embed, wait=True)
thread = await interaction.channel.create_thread(name="Response Thread", message=msg)
this worked thank you so much! 

show code? you shouldnt be using fetch_guild btw, did you make sure your guild id is an int
Why he shouldn't? If his cache is not enabled he should. Otherwise getch_guild or whatever it's named in dpy
fetch_guild doesnt have the proper member/channel data
No way discord gave me free nitro but I am in Russia ๐
requires chunking
He didn't mention anything about members did he
generally people would, but sure, its so incase they have any followups
I don't think something like "getch" exists in d.py
oh my bad
async def send_bot_help(self, mapping):
"""triggers when a `<prefix>help` is called"""
ctx = self.context
embed = HelpEmbed(title=f"{ctx.me.name} Help")
embed.set_thumbnail(url=ctx.me.avatar.url)
usable = 0
for cog, commands in mapping.items():
if filtered_commands := await self.filter_commands(commands):
amount_commands = len(filtered_commands)
usable += amount_commands
if cog:
name = cog.qualified_name
description = cog.description or "No cog description"
else:
name = "No Category"
description = "Commands with no category"
embed.description = f" Thanks for using **Axntron**. \n If you'd like to view help for commands, you can use ,help <command> and for more help you can join my [support server](). \n \n My prefix is `,`. \n \n `,help mod` \n> :**Useful Moderation Commands.** \n:icons: `,help dank` \n> :**Useful Dank Commands.** \n:Icons_utility: `,help utility` \n> :**Useful Utility Comands.** \n:fun: `,help fun` \n> :**Useful Fun Commands.** \n `,help admin` \n> :**Useful Admin Commands.** \n `,help CoolKidsClub` \n> :**Useful text modifying commands.**"
embed.color=0xffffff
view = helpowo2()
view.message = await self.send(embed=embed,view=view)
Help embed is not sent when I use a?help, no errors show up
whats your code when you set the HelpCommand to the bot
client.help_command = MyHelp()
hmm there should be at least 1 error there
yea
you shouldnt await bot.get_guild, its not coroutine
!d discord.Guild.system_channel
property system_channel```
Returns the guildโs channel used for system messages.
If no channel is set, then this returns `None`.
also, there is no reason to censor your guild id, no one can do anything with it
Donโt get any
hmm
get_guild is from cache, it doesnt do any api calls
how did you start the bot? is it with bot.run?
No
show it
If __name == โ__main__โ:
client.run(token)
i see, do you have an error handler? could be a suppressed error
What are some decent ways of deploying discord bots ?
Railway looks pretty good to me
So far I've just been using a VPs with docker
Imagine joining a server and leaving instantly
Wtfff
I do that about 20 times a day whenever I see an invite link
Morbid curiosity
๐ ** **
Got different for each command
Is it possible to make it so you can only choose one option from the select menu and after it's selected, it expires?
VPS with docker is one of the best
I mean it already can be considered deployment, what exactly do you mean by "deploy"
no global ones? particularly w/ on_command_error
Yes, just provide required kwarg in constructor and define callback
See examples on your lib github repo
@radiant bough if you shared code before could you please reply to that message? If not, please send the code that does not work
Yeah that's why I said "whatever it's named in dpy", might not exist at all, I apologize for misinformation then
!d discord.ext.commands.Bot
class discord.ext.commands.Bot(command_prefix, *, help_command=<default-help-command>, tree_cls=<class 'discord.app_commands.tree.CommandTree'>, description=None, intents, **options)```
Represents a Discord bot.
This class is a subclass of [`discord.Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client") and as a result anything that you can do with a [`discord.Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client") you can do with this bot.
This class also subclasses [`GroupMixin`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.GroupMixin "discord.ext.commands.GroupMixin") to provide the functionality to manage commands.
Unlike [`discord.Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client"), this class does not require manually setting a [`CommandTree`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CommandTree "discord.app_commands.CommandTree") and is automatically set upon instantiating the class.
async with x Asynchronously initialises the bot and automatically cleans up.
New in version 2.0.
Could you help me with that?
@vale wing
@client.listen("on_command_error")
async def idk123(ctx, error):
if isinstance(error, CommandNotFound):
e = discord.Embed(description=f"Error: \nCommand sent by user not found.\n", color=discord.Colour.dark_theme())
await ctx.reply(embed=e,delete_after=15)
if isinstance(error, MissingPermissions):
e = discord.Embed(description=f"Error: \nUser is not having the required permissions.\n", color=discord.Colour.dark_theme())
await ctx.reply(embed=e)
Is that all
if thats it, then you're indeed suppressing the error, d.py stop printing errors if you have event/listeners on on_command_error
yes
what should i do then, remove this?
Then un-handled errors wouldn't be visible
may wanna re-raise/reprint errors such as this, ```py
if ...:
elif ...:
else:
raise error
What should I use to get my botโs avatar url
Normally
!d discord.ClientUser.display_avatar
property display_avatar```
Returns the userโs display avatar.
For regular users this is just their default avatar or uploaded avatar.
New in version 2.0.
then just .url
ty itโs fixed
so did you get the error now? there should be a .send attr error in that help command
It was the avatar url
i see
I had the default one
:-:
:-:
.-.
exactly that
i wasnt sure whether its common practice or not
Yeah docker is one of recommended ways to run discord bots
referring moreso to the hosting
but if vps is common I'll jhust stick to that
The only proper hosting is with a VPS (or self hosting)
import discord
from discord.ext import commands
from discord.ext.commands import has_permissions
@commands.command()
@has_permissions(manage_message = True)
async def clear (self, ctx, amount):
if amount == 0:
await ctx.send ("Veuillez entrer un nombre de message a effacer.")
elif amount >= 1:
await ctx.channel.purge(limit=amount)
Traceback (most recent call last):
File "e:\SSD\Python\Code\Projets\DevBot\DiscordBot\cogcmd\moderation.py", line 9, in <module>
class moderation_cmd(commands.Cog):
File "e:\SSD\Python\Code\Projets\DevBot\DiscordBot\cogcmd\moderation.py", line 87, in moderation_cmd
@has_permissions(manage_message = True)
File "C:\Users\Mathieu\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 2187, in has_permissions
raise TypeError(f"Invalid permission(s): {', '.join(invalid)}")
TypeError: Invalid permission(s): manage_message
manage_messages=True its plural
note that has_permissions or any other decorator involving permissions follows the discord.Permissions attribute
!d discord.Permissions.manage_messages
Returns True if a user can delete or pin messages in a text channel.
Note
Note that there are currently no ways to edit other peopleโs messages.
thank you.
welcome 
how can i write it this way:
if the messages are older than 14 days then: return and send "blablabla"?
!d discord.Message.created_at
property created_at```
The messageโs creation time in UTC.
Source code: Lib/datetime.py
The datetime module supplies classes for manipulating dates and times.
While date and time arithmetic is supported, the focus of the implementation is on efficient attribute extraction for output formatting and manipulation.
Use datetime.datetime.now() and conv to seconds and conv created_at to secs and minus it and check if the seconds is lower or upper than 14 days in seconds or simply use timedelta
Hey guys, How to make in discord module (slash commands):
A player enters a flight code, and some other, and if a player uses other command it will show.
Save the code in a db, then just get that value
could you make this ocde?
No, do it yourself
So create a database, and how to save it in database?
Do you need to keep this code even after restarting the bot?
If not, just use a variable
uhh yes
So I have that code:
Set Flight Command
@client.tree.command(name="setflight", description="Set's Next Flight")
@discord.ext.commands.has_role("")
async def setflight(flight_Code:str, Plane:str, AvabilableClasses:str, Departure:str, Arrival:str):
#Flight Command
@client.tree.command(name="flight", description="Check info about next flight!")
async def flight(Interaction:discord.Interaction):
embed = discord.Embed(title="Flight:", value="", color=0x800080)
embed.add_field(name="Flight Code:", value="", inline=False)
embed.add_field(name="Plane:", value="", inline=False)
embed.add_field(name="Avabilable Clases:", value="", inline=False)
embed.add_field(name="Departure:", value="", inline=False)
embed.add_field(name="Arrival:", value="", inline=False)
await Interaction.response.send_message(embed=embed)
And I want to those "flight_code", Plane etc. To be in flight in value
This naming convention is somewhat outstanding
Okay..? Yeah use a database
I am making bot for my friend (for his airline)
PascalCase in parameters names
sqlite or postgres
json?
Json is not a database
Make own database ๐ค๐
Ok So I don't want to install anything.
why?
which dosen't require anything just make a file
sqlite is file-based
Cause I will later make it on repl.it
and postgres?
that's even worse
You already need to install dpy
..?
.
Still I prefer repl
Just try VSC or PyCharm and you will change your mind
am using pycharm
Then why use replit
for hosting
ye
๐คฆโโ๏ธ planes are definitely gonna crash
So can you help me?
.
What do you want? I already answered you
Ephemeral file system, you just can't save data
How to create database
There probably are ways in replit but you should ask in corresponding place, i.e. their server/forum/support
which one? are you still gonna use replit?
ye sl
replit is not a good option for hosting a discord bot
Yeah, MySQL Database (without installing)
I can use what I want.
How are you gonna use mysql on replit
I never said you can't
Sure, see what happens
How can you have any server database without installing it ๐ง
Unless it is hosted by someone
that is not mysql
Why can't you just get a free tier of VPS
cause $$
@commands.command()
@has_permissions(manage_messages = True)
async def effacer (self, ctx, amount=0):
if amount == 0:
await ctx.send ("Veuillez entrer un nombre de message a effacer.")
return
elif amount > 0 and amount <= 99:
amount=amount +1
deleted_messages = await ctx.channel.purge(limit=amount, after = datetime.utcnow()-timedelta (days=14))
await ctx.send ("les message sont infereieurs ร 14 jours", delete_after=3)
await ctx.send (f"{deleted_messages} messages ont รฉtรฉ supprimรฉs.", delete_after=5)
Traceback (most recent call last):
File "C:\Users\Mathieu\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\bot.py", line 1349, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\Mathieu\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 1023, in invoke
await injected(*ctx.args, **ctx.kwargs) # type: ignore
File "C:\Users\Mathieu\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 238, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In content: Must be 2000 or fewer in length.
ur issue is
await ctx.send ("les message sont infereieurs ร 14 jours", delete_after=3)
await ctx.send (f"{deleted_messages} messages ont รฉtรฉ supprimรฉs.", delete_after=5)
u have a lot of deleted_messages
Invalid Form Body
In content: Must be 2000 or fewer in length.
I don't understand, what does that mean?
impossible.... why to long?
its a command...
Hi there, I'm having issues running my code. It runs fine but the event doesn't work...
import discord
from discord.ext import commands
class VIPRoleCog(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.Cog.listener()
async def on_member_update(self, before, after):
status = after.status
if status == discord.Status.online or status == discord.Status.idle:
if "invitelink" in after.activity.name.lower():
guild = self.bot.get_guild(1066829912943636510)
role = discord.utils.get(guild.roles, id=1066829913031712773)
await after.add_roles(role)
channel = self.bot.get_channel(1074386028745457777)
await channel.send(f"{after.mention} has been awarded vip role for having invitelink in their status")
def setup(bot):
bot.add_cog(VIPRoleCog(bot))```
It's meant to give the user the vip role when their status is set to the invitelink, but it's not working...
await ctx.send ("les message sont infereieurs ร 14 jours", delete_after=3)
await ctx.send (f"{deleted_messages} messages ont รฉtรฉ supprimรฉs.", delete_after=5)
that command is sending a message in the discord chat
ok... but it's not working like at all
neither work
!d discord.Embed
Sorry, I just mean our spam filter will delete anything containing .gg/something.
yea make sence
Hmmm, wrong one
it no long message...
thats what the error says ๐คทโโ๏ธ
You're sending a list of message objects
no send here
And the message object's repr is huge
everytime u do !effacer 5 u get that error?
do
print(deleted_messages)
to see what it is
A list of messages, obviously
yeah but it's to show him that it can contain a lot of messages
Sure
i think what u should instead do is
await ctx.send (f"{len(deleted_messages)} messages ont รฉtรฉ supprimรฉs.", delete_after=5)
if i write:
elif amount > 0 and amount <= 99:
amount=amount +1
deleted_messages = await ctx.channel.purge(limit=amount, after = datetime.utcnow()-timedelta (days=14))
print (len(deleted_messages))
await ctx.send ("les message sont infereieurs ร 14 jours", delete_after=3)
await ctx.send (f"{len(deleted_messages)} messages ont รฉtรฉ supprimรฉs.", delete_after=5)
the bot the me the number of message deleted, but the number of message are not deleted...
just send 2 message at the end of code
try
deleted_messages = await ctx.channel.purge(limit=amount)
cause i think
after = datetime.utcnow()-timedelta (days=14)
is looking for old messages
Not really
You know that it is better to explain why instead of just saying "Not really"
The code already explained itself
That's not a good explanation.
after is set to looking for any messages that is sent after 14 hours days ago
Wait not hours
Eh, it's already explained
It seems that you are struggling.
u dont have a dollar?
Sure
he asked why there is no free tier. Companies would have to fork in money for free tier
there are free tiers, and he asked them why they didnt just use a free tier plan for hosting
@naive briarwhy are the messages not being deleted?
dunno about sql dedicated servers but you can get a 2gb ram and 20gb storage vps for $0.97 per month at OVHCloud
no thanks!
sounds unreliable
๐ค
id stick to aws
What do you think you're winning lmfao
grats now ur bot will become very slow in the near future
good job for not using the stuff everyone recommends because its reliable
heres a medal
it isn't lol
aka work smarter not harder
152ms
already slow
for me it is fast
using janky shit is NOT working smarter
read what i said catgal will not help you
after = datetime.utcnow()-timedelta (days=14)
is not a check?
le paramรจtre recherche un ancien message
14 jours
because I want that if the messages to be deleted are greater than 14 days then I have to send an error message in the channel
si vous le supprimez simplement. Il devrait juste supprimer le dernier x nombre de messages
It is
yes thats what u have right now
but the way it's coded, the messages don't delete each other
because the messages aren't older than 14 days
unless you have messages that ARE older than 14 days that aren't being deleted then thats a different issue
And there's no difference between with and without, because Discord will just ignore the message that's older than 14 themselves
no I want to delete messages that are more recent than 14 days
then change the day
that's what i already have though
yea im telling u that you should change that number to something u like
for example 1 or 4
There's no point changing it
^ And this is not true, by the way
"free tier" and $ are kinda opposite don't you find
You have to attach a card to all of services, that's true, but you don't spend anything on free tier
i thought u where saying why dont companies offer free tier
i miss read
Happens
Now do it without discord.py ๐
Just add a few megabytes of data to that json file and we will see
mfw when json can't save discord IDs without rounding them off
what?
shwo your code
This is a certified 53-bit resolution moment
53-bit resolution COOL
ik
now i get why IDs in djs are strings
Depends on what version/what JavaScript engine your using
The very old versions will prob not support uint64 whereas newer version do have support
Js... ๐ณ
I would actually just keep all int64 numbers in a string if your using JavaScript
Since pretty much every API does the same
my reaction to coverting string to int is possible
Aren't they serialised as strings in API as well?
yes they are
i hate async def on_message every time try to make the commands work it ignores it i even attempted to await bot.process.commands thingy but never worked as intended
@bot.event
async def on_message(message):
if message.author.id == bot.user.id:
return
if bot.user in message.mentions:
await message.channel.send("Hello This Is Mention Test")
if message.content.lower() in ["any","blacklisted","word"]:
await message.delete()
await message.author.send("""There's Something Called "No Swearing" Rule bruh""")
await bot.process_commands(message)
#Help commands
@bot.command()
async def test(ctx):
await ctx.send("it works")
because you're doing it wrong
await bot.process_commands should be outside of those conditions
Your bot.process_commands is in an if block
you should actually just change the .event decorator to .listen(), cleaner and simpler
Just move it down one indent or set it as listener
i tried it but commands work but others didn't
I have a mistake in my code for a long time, and I still don't understand how to fix it. Someone help me?
Code:
@bot.event
async def on_message_edit(message_before, message_after):
embed = discord.Embed(
title="{} edited a message".format(message_before.author.name),
description=
f"From: **{message_before.guild} / {message_before.guild.id}**",
color=0xFF0000)
embed.add_field(name=message_before.content,
value="This is the message before any edits.",
inline=True)
embed.add_field(name=message_after.content,
value="This is the message after editing.",
inline=True)
channel = bot.get_channel(1234567)
await channel.send(embed=embed)
Error:
Traceback (most recent call last):
File "/home/runner/HELPER/venv/lib/python3.8/site-packages/discord/client.py", line 409, in _run_event
await coro(*args, **kwargs)
File "main.py", line 4385, in on_message_edit
await channel.send(embed=embed)
File "/home/runner/HELPER/venv/lib/python3.8/site-packages/discord/abc.py", line 1538, in send
data = await state.http.send_message(channel.id, params=params)
File "/home/runner/HELPER/venv/lib/python3.8/site-packages/discord/http.py", line 744, in request
raise HTTPException(response, data)
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In embeds.0.fields.1.name: Must be 256 or fewer in length.
Hi all, have any examples how to read command + few arguments on nextcord, thanks
thank you
hey, i can change a button disabled=True by clicking other button?
Yes
how?
why is the final message taking a long time to appear? (about 2 seconds)
@commands.command()
@has_permissions(manage_messages = True)
async def supp (self, ctx, amount=0):
if amount == 0:
await ctx.send ("Veuillez entrer un nombre de message a effacer.")
return
elif amount > 0 and amount <= 99:
if amount == 1:
amount +=1
await ctx.channel.purge(limit=amount)
amount -= 1
await ctx.send (f"{amount} message a รฉtรฉ supprimรฉs!", delete_after=5)
return
because purge uses 2 API calls, history + bulk delete, hence its "slower" for the final message to appear
instead of purge I can use delete or not?
now why would you do that? its not like its faster either
how to make faster in this case?
you can't, thats how it is, purging isnt instant
async with typing(*, ephemeral=False)```
Returns an asynchronous context manager that allows you to send a typing indicator to the destination for an indefinite period of time, or 10 seconds if the context manager is called using `await`.
In an interaction based context, this is equivalent to a [`defer()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Context.defer "discord.ext.commands.Context.defer") call and does not do any typing calls.
Example Usage:
```py
async with channel.typing():
# simulate something heavy
await asyncio.sleep(20)
await channel.send('Done!')
```...
tks
i'm planning tio split my function by operator, but it doesn't seems to separate:
args_result = args.split("+", "-", "*", "/")
What is args
this:
async def roll(self, ctx, args, aliases = ['r', 'diceroll', 'dice_roll', 'dice']):
an input
it seems to work until this:
when hit th args.split it erroes
or better, don't seems to work
what is the correct way to do what i was trying to do?
str.split(sep=None, maxsplit=- 1)```
Return a list of the words in the string, using *sep* as the delimiter string. If *maxsplit* is given, at most *maxsplit* splits are done (thus, the list will have at most `maxsplit+1` elements). If *maxsplit* is not specified or `-1`, then there is no limit on the number of splits (all possible splits are made).
If *sep* is given, consecutive delimiters are not grouped together and are deemed to delimit empty strings (for example, `'1,,2'.split(',')` returns `['1', '', '2']`). The *sep* argument may consist of multiple characters (for example, `'1<>2<>3'.split('<>')` returns `['1', '2', '3']`). Splitting an empty string with a specified separator returns `['']`.
For example:
is channel id string or integer
i have installed discord.py extension but its giving error module not found in vs code , any way to fix ?
integer
okay, now i'm trying this and i don't know why it's not working:
args_result = re.split(r'[+-*/]', args)
What is installed discord.py extension
like did "pip install discord"
me?
yes
No
!d re.split
re.split(pattern, string, maxsplit=0, flags=0)```
Split *string* by the occurrences of *pattern*. If capturing parentheses are used in *pattern*, then the text of all groups in the pattern are also returned as part of the resulting list. If *maxsplit* is nonzero, at most *maxsplit* splits occur, and the remainder of the string is returned as the final element of the list.
```py
>>> re.split(r'\W+', 'Words, words, words.')
['Words', 'words', 'words', '']
>>> re.split(r'(\W+)', 'Words, words, words.')
['Words', ', ', 'words', ', ', 'words', '.', '']
>>> re.split(r'\W+', 'Words, words, words.', 1)
['Words', 'words, words.']
>>> re.split('[a-f]+', '0a3B9', flags=re.IGNORECASE)
['0', '3', '9']
it seems to not treat "+" as a separator
Of course not
i see, then how do i use it to detect operators as a split thing?
!e
import re
pattern = re.compile(r"[\+\-\*\\/]")
print(pattern.split("cat+meow-kitty"))
@naive briar :white_check_mark: Your 3.11 eval job has completed with return code 0.
['cat', 'meow', 'kitty']
Understand its pattern (although I also don't know shit about regex)
i don't know why it's not starting to roll
result = []
total = 0
meta = []
if "d" in inp:
print("rolling...")
res = int(inp.split('d'))
print(res)
sub_r = []
z = 0
while(z < res[0]-1):
if res[1] == "f" or res[1] == "F":
sub_r.append(random.randint(1, 6))
if sub_r == range (1, 2):
sub_r[z] = "-"
elif sub_r == range (3,4):
sub_r[z] == "0"
else:
sub_r[z] == "+"
else:
sub_r.append(random.randint(1, res[1]))
z = z+1
result.append(sub_r)
for x in result:
total = total+x
meta.append(result, total)
return meta```
it's not even entering into if "d"
it's a pretty interesting function as well
The same
iirc discord alone is a broken mirror of discord.py
so should be discord.py, its not relaly the same
How run 2 deferent sounds parallely by this method on one voice channel nextcord.FFmpegOpusAudio?
class SimpleView(discord.ui.View):
@discord.ui.button(label='Crear un ticket', custom_id='Tickets', style=discord.ButtonStyle.success, emoji='๐ง')
async def Ticket_Create(self, interaction:discord.Interaction, button:discord.ui.Button):
view = Menu_select
await interaction.send(view=view)
does someone know how i should call the Menu_select class? This is wrong:
await interaction.send(view=view)
how?
By calling the class
yea, I already did, but I have an error
It's hard for us to help you when we don't know what the error is
Could you post it?
AttributeError: 'Interaction' has no attribute 'send'
It's interaction.response.send_message
Needs to be a response.
if I do this it prints this: <class 'main.Menu_select'>
On discord?
yeap
Does this happen when you press the "Crear un ticket" button?
yeap
And could you post your code?
He's asking for the updated code
Can you show us your code
the code?
Yes
I can speak Robin so I can translate.
๐คญ
class SimpleView(discord.ui.View):
@discord.ui.button(label='Crear un ticket', custom_id='Tickets', style=discord.ButtonStyle.success, emoji='๐ง')
async def Ticket_Create(self, interaction:discord.Interaction, button:discord.ui.Button):
await interaction.send(Menu_select)
this is the code
Should be view=Menu_select(...)
Where ... is the parameters that the class takes (if any)
class SimpleView(discord.ui.View):
@discord.ui.button(label='Crear un ticket', custom_id='Tickets', style=discord.ButtonStyle.success, emoji='๐ง')
async def Ticket_Create(self, interaction:discord.Interaction, button:discord.ui.Button):
view = Menu_select
await interaction.send(view=view)
like this?
What changed?
Oh no you have to pass the class in the kwarg view and also initialize it.
There are no dumb errors
Yeah, I mean what a dumb mistake
you now, Im form spain, sorry for the expresions๐
A lot of us aren't English natively.
Robin
FWIW English ain't my first language either
Can I test something on you Robin? :3
I suppose
@sick birch Did this ping you?
It did
But it has a weird icon next to it
Looks like a bell with the letter z
Supposed to be a silent message, rigged.
== Raw message ==
@sick birch Did this ping you?
Sike
Hidden
actually it's not even entering the funtion:
i made a debug but it didn't entered the funtion
Actually do you even call the function
Pasting large amounts of code
If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
also @vale wing i will probably need suggestions and help to simplify the variables
so they would be more understandable
like, better name
Anyone know if it possible to edit wehbook image ?
```webhook_id = "myid"
webhook_token ="mytoken"
url = f"https://discord.com/api/webhooks/%7Bwebhook_id%7D/%7Bwebhook_token%7D"
payload = {
"name": "Myname",
"avatar": "base64image "
}
requests.patch(url, json=payload)```
Cuz with this only my name edits
did you find it?
probably not ||guess it's struggling with my spaghetti XD||
Hey i've got a weird bug
it's saying an option is already being used in my dropdown im creating
new_option = Option(label=f"{attacker_name}", value=f"att{attacker_id}{end}")
if new_option not in options:
options.append(new_option)```
but i have this code
in a for loop, then it makes the options at the end
it's impossible right?
guys why this is not turning my bot online? ```import discord
import asyncio
client = discord.Client(intents=discord.Intents.default())
TOKEN = 'somerandomnumbersandletters'
@client.event
async def on_message(message):
if message.author == client.user:
return
await asyncio.sleep(4)
async with message.channel.typing():
await asyncio.sleep(2)
await message.channel.send("test")
client.run(TOKEN)and this doesimport discord
import asyncio
import torch
from transformers import pipeline
client = discord.Client(intents=discord.Intents.default())
TOKEN = 'somerandomnumbersandletters'
generator = pipeline('conversational', model='EleutherAI/gpt-neo-2.7B')
prompt = 'This is an ai chatbot based on gpt neo'
@client.event
async def on_message(message):
res = generator(prompt, max_length=40, do_sample=True, temperature=0.9)
if message.author == client.user:
return
await asyncio.sleep(4)
async with message.channel.typing():
await asyncio.sleep(2)
await message.channel.send(res[0]['generated_text'])
client.run(TOKEN)```
the first one works the secone doesnt work
how can i make this slash command's name have spaces
@bot.tree.command(description="Clears the specified stat")
async def clear_stat(interaction : discord.Interaction, member : Optional[discord.Member], stat : stat_choices):
async def SendMessage(ctx):
package.setup.setsettings.settranslationlanguage_hindi()
print('Hindi translation language selected')
await ctx.send('Hindi translation language selected')``` how RUN this from PYTHON code?? not from chat by command.....
you need to use slash subcommands or slash subgroup, the maximum is 3, something like /foo bar hiii (note that the example uses a subgroup with a subcommand)
that message isn't for you
not hindi ok..
in your case it would be convenient to have a simple python function where you call your things, then in your command body function you'll call the python function and respond to the user
so in this and the question I do not understand how to register such a function ๐
tbh there are a lot of wrong things here
- you shouldn't use a json file as database, its purpose is not that
- even if you wanted to use a json file, reading and loading a file is a blocking call, that means the event loop will be affected by this, to put it simple your Bot may be some seconds behind the API and may lose connection because of it
use a database
with an async driver
I would recommend PostegreSQL but you should look into relational databases to use it well
or you could use MongoDB
that's a document based database
the important thing here is that you must use async drivers/clients to connect to the databases and to do things
How do I create this subgroup?
does discord.InteractionResponse.send_message() not return the just sent message?
how can I get the object for the just sent message?
!d discord.app_commands.Group
class discord.app_commands.Group(*, name=..., description=..., parent=None, guild_ids=None, guild_only=..., nsfw=..., auto_locale_strings=True, default_permissions=..., extras=...)```
A class that implements an application command group.
These are usually inherited rather than created manually.
Decorators such as [`guild_only()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.guild_only "discord.app_commands.guild_only"), [`guilds()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.guilds "discord.app_commands.guilds"), and [`default_permissions()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.default_permissions "discord.app_commands.default_permissions") will apply to the group if used on top of a subclass. For example:
```py
from discord import app_commands
@app_commands.guild_only()
class MyGroup(app_commands.Group):
pass
```...
you should fetch it ig
ah how?
I'm not sure but you could use
!d discord.Interaction.original_response
await original_response()```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Fetches the original interaction response message associated with the interaction.
If the interaction response was a newly created message (i.e. through [`InteractionResponse.send_message()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.InteractionResponse.send_message "discord.InteractionResponse.send_message") or [`InteractionResponse.defer()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.InteractionResponse.defer "discord.InteractionResponse.defer"), where `thinking` is `True`) then this returns the message that was sent using that response. Otherwise, this returns the message that triggered the interaction (i.e. through a component).
Repeated calls to this will return a cached value.
it fetches the original message, I want the object for the just sent message by send_message() function
no this fetches the first interaction response
If the interaction response was a newly created message (i.e. through InteractionResponse.send_message() or InteractionResponse.defer(), where thinking is True) then this returns the message that was sent using that response.
ah thanks didn't read the second part ๐
no problem
also the name is confusing
usually that method is not used in this way
can sum1 help with this
update your discord.py
how are you below discord.py 1.5
how do i pass an enum as an option in a slash command?
do i have to do an autocomplete thing?
i think i found it
it's the autocomplete decorator
How could I set an cooldown on message? Save times in cache and compare time now?
I think d.py had some cooldown decorators. Never used them though. This would be the manual solution, yes
!custom-cooldown
Cooldowns in discord.py
Cooldowns can be used in discord.py to rate-limit. In this example, we're using it in an on_message.
from discord.ext import commands
message_cooldown = commands.CooldownMapping.from_cooldown(1.0, 60.0, commands.BucketType.user)
@bot.event
async def on_message(message):
bucket = message_cooldown.get_bucket(message)
retry_after = bucket.update_rate_limit()
if retry_after:
await message.channel.send(f"Slow down! Try again in {retry_after} seconds.")
else:
await message.channel.send("Not ratelimited!")
from_cooldown takes the amount of update_rate_limit()s needed to trigger the cooldown, the time in which the cooldown is triggered, and a BucketType.
great thanks
when you understood my code, please ping me.
They never will
updating never....:)
how do i take a list of users in app_commands?
if welcome_channel:
embed = discord.Embed(title=f"Welcome {member.name}!",
description=f"Thank you for joining our server! Please take a moment to read the "
f"{discord.utils.get(member.guild.channels, name='rules')} and introduce yourself in the "
f"{discord.utils.get(member.guild.channels, name='introductions')} channel.",
color=0x00ff00)
embed.set_thumbnail(url=member.avatar_url)
await welcome_channel.send(embed=embed)
Hey question, how would I get it to put #introductions/#rules as channel links in the embed?
oh maybe cuz i missed the # oops
How could I fix this?
async def help(self, ctx):
embed = nextcord.Embed(
title="Help", description="List of available commands:", color= nextcord.Color.green())
for i in self.bot.cogs:
cog = self.bot.get_cog(i.lower())
commands = cog.get_commands()
data = []
for command in commands:
description = command.description.partition('\n')[0]
data.append(f"{command.name} - {description}")
help_text = "\n".join(data)
embed.add_field(name=i.capitalize(),
value=f'
{help_text}
', inline=False)
embed.set_thumbnail(url='https://cdn.discordapp.com/attachments/1068706276768497836/1071609900469334056/pngtree-eagle-head-logo-png-image_8704115.png')
embed.set_image(url='https://cdn.discordapp.com/attachments/1056648270216171630/1059649382456234104/standard.gif')
await ctx.author.send(embed=embed)```
i see, my code is clusterf@cked
!d discord.ext.commands.Bot.cogs
property cogs```
A read-only mapping of cog name to cog.
It's already returning the cogs, why are you getting it again
I'm doing it because of my help command
so it can show you the listed command and etc
And? I'm saying that it has already returned the cogs
So then how can we fix this?
@naive briar
??
@naive briar bro this is a custom help command and it used to work and I never messed around with the code this is how it worked
Why are you asking for help if it works then ๐คท
There's no point asking for help if you don't accept it
re-read @naive briar
I don't know what to say anymore, I already said that the cogs attr already returned the cogs and there's no point getting it again
re-read what catgal said
a read-only mapping of cog name to cog.
how do you install discord.py
pip install discord.py
it doesnt work
Install pip first
how
Yeah you need to get a text editor
sorry sorry im new
which do you recommend
I recommend VScode
for multiple coding languages but if you're gonna only stick with Python then Pycharm
hm ok
wait what
python -m pip install discord.py
what is the point of that pip is already installed with python ๐
๐คท
its doesnt workk
what does it say
whats the error
this
how did you install python @coral glen
???????? send what it says again
try reinstalling python with pip maybe
how
you probably disabled it if you did custom install
oh
u didn't install properly why do u have python.exe in desktop?
ur paths are not set properly either
I'm wanting to send two messages for the response of an interaction how can I do this. Well the issue is I'm responding with another menu but I also want it to have a message
๐ต
!d discord.Interaction.followup
Returns the follow up webhook for follow up interactions.
If I want the menu to be sent after the message should I just put the view=view in the followup and the message in the response?
yeah
so this time just "Install Now"?
go with default and dont forget to select the check box with add python to path
?
yeah
@winged cloud don't make your repls public, anyone can access them and view your token
yeah
??
you have to go customize installation and then check everything
the default installation don't install pip
pip is supposed to be installed by default, but in the case it isnt installed you can use py -m ensurepip to bootstrap it, then retry pip install discord.py
I've installed python a lot of time and in all cases when it was default installation, pip was never installed
it's weird
welp i never had the same issue
maybe it's a new "feature" to let the user choose
better off installing pip by doing sudo apt update -> sudo apt install python3-pip
they're on a windows machine, and you also wouldnt want to be using the system python for your projects
oh ill try that
i keep forgetting that linux isnโt the same as windows
run your terminal as administrator
ok
install python again with full check on custom, it will make less errors
weird.
gives me the same result
damn bot
no changes?
yes
mk
4th time uninstalling python within an hour ๐ญ
lmao
nah, modify installation then custom install
๐ฟ alr did it
any error with pip install discord.py?
there on windows
check all
ok
if you do python it's useful to have more tools in your hand and it's light anyway
no big deal to have 10mo more
you really dont need to check all of them
true, but at least it's efficient
if anything its less efficient, you're asking it to do things you wont need
maybe don't install debugging symbols lol
but the PATH is important
and precompile should make the code run faster
for all user should not be a problem if the user is alone on it's computer


(for future reference)
