#discord-bots
1 messages · Page 870 of 1
I'm getting an error for my calculator command. Here's the code:
blocks = [
block.MathBlock(),
block.RandomBlock(),
block.RangeBlock(),
]
self.engine = Interpreter(blocks)
@commands.command(aliases=["calc"])
async def calculate(self, ctx, *, query, message):
"""Math"""
query = query.replace(",", "")
engine_input = "{m:" + query + "}"
start = time.monotonic()
output = self.engine.process(engine_input)
end = time.monotonic()
output_string = output.body.replace("{m:", "").replace("}", "")
try:
fmt_str = f"{float(output_string):,}"
except ValueError:
fmt_str = output_string
e = discord.Embed(
color=await ctx.embed_color(),
title=f"Input: `{query}`",
description=f"Output: `{fmt_str}`",
)
e.set_footer(text=f"Calculated in {round((end - start) * 1000, 3)} ms")
await ctx.send(embed=e)
and here's the error:
This is in a cog btw
show on_command_error
wdym
show your on_command_error
i dont understand, i don't think I have one.
full error?
This is all that shows up on the console
are you sure?
yes
yea
*args and **kwargs
These special parameters allow functions to take arbitrary amounts of positional and keyword arguments. The names args and kwargs are purely convention, and could be named any other valid variable name. The special functionality comes from the single and double asterisks (*). If both are used in a function signature, *args must appear before **kwargs.
Single asterisk
*args will ingest an arbitrary amount of positional arguments, and store it in a tuple. If there are parameters after *args in the parameter list with no default value, they will become required keyword arguments by default.
Double asterisk
**kwargs will ingest an arbitrary amount of keyword arguments, and store it in a dictionary. There can be no additional parameters after **kwargs in the parameter list.
Use cases
• Decorators (see !tags decorators)
• Inheritance (overriding methods)
• Future proofing (in the case of the first two bullet points, if the parameters change, your code won't break)
• Flexibility (writing functions that behave like dict() or print())
See !tags positional-keyword for information about positional and keyword arguments
while True: await asyncio.sleep(60) timestamp = datetime.datetime.now() await message.edit(embed=embed)
Can someone tell me why this doesn't work?
It doesnt update the embed, it just show it edited it but doesnt update the time
Oh thanks
Is there also any way to show how many people are on Online for example=
or on do not disturb?
Or Oflline?
!d discord.Member.status
property status: discord.enums.Status```
The member’s overall status. If the value is unknown, then it will be a [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)") instead.
anyone help me with this problem?
File "c:\Users\sweti\OneDrive\Skrivbord\drive-download-20220301T163300Z-001\main.py", line 50, in <module>
bot.run(TOKEN)
Hey @quaint epoch!
You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.
!paste
I was wondering how i would be able to make something like this (a reaction role command).
whats Member.guild_avatar?
on_reaction_add or on_raw_reaction_add
brb found a bug
dm = await member.create_dm() this is an extra step/api call
you can just Member.send() in 99% cases
i wanted to be safe
yeah sorry, fixed a bug - https://paste.pythondiscord.com/uviwewixaj
be more specified, it is not suggested to use on_reaction_add because it triggers the reactions which are in the bot cache
alr
Someone gimme the funniest piece of code ever
so the code will work if the reaction is created when the bot is online but when you turn it offline or the reaction was created before the bot came online the bot will not see when a reaction will be addedd
print('funniest piece of code ever')
thank yoi
@bot.event
async def on_message(msg): if not isinstance(message.channel, discord.DMChannel) :await msg.delete(), await msg.author.kick()```
thanks
funny 100, functionality 0
i sure love dm'ing bots
why would it not work lol
how can you kick and author from a dm? you can close a dm but how would you kick
if not isintance
nice excuse
OW
you cant have two colons on the same line without an indent
if python was a language that you can condense all in one line without lambdas, i would not program it
you can condense lots of code into one line
but all of it?
dont program it
a lot of it, tes
new apple product
give me the code for a command and ill condense it to one line

you just want me to fix your code anyway
anywhooo, i have math now cya
no it's fixed, im using this as an excuse to have someone use it
no one uses it
how do I add allies on command?
the code doesnt look very efficient in the slightest, not sure why someone would use it
@command(aliases=[...])
@bot.command(aliases=[])
ty
oh yeah math cya
what about emojis, how do I add them (custom ones)?
just put them in the alias
.
because
no I meant like for them to send it
put the custom emoji code into the alias
<name:id>
yeah but it doens't owrk like that
why not?
what are you trying to do?
send the emoji I made
Hey I have @bot.event which sends a message when a certain user comes online. But the bot sends the message 4 times.
you want to send the emoji you made?
remove the ~1
Can someone help me?
what does your code look like?
try printing after.status
also you dont need to put str around after.id, just remove the str and remove the quotes around the id so its a bare int
does the bot have access to that emoji (aka in that server) and emoji intents?
emoji intents? not sure about that. lemme check
I did this, but still doesn't work
Do you mean that under "await channel.send(f "IDK")" I should write "print(after.status)?
just print the status somewhere to debug it
are you sure you copied the emoji correctly?
Okay I've done it but he still spamming the message
what is printing?
online but 5 times and than i stopped the bot
odd
Just use disnake.Intents.all() if you are not verified yet
odd = ! even
I do not know what this is
How?
This emoji, 
948275750820265984
@manic wing @cedar stream
put \ before it and copy it
Do you know what should i do?
thats after it
can anyone help me please?
no, its triggering multiple times for some reason meaning you've done something wrong with your code but im not gonna spend 2 hours fixing it with you
I should do it in the code?
This would get triggered, if say, the user stayed online but updated their profile (status)
You want to check both the before status and after status
i was suggesting you use that to copy the emoji but it looks like you've copied it fine
Hi Robin
bruh it doesn't work..
anyone help me to solve this?
File "C:\Users\sweti\OneDrive\Skrivbord\drive-download-20220301T170315Z-001\main.py", line 50, in <module>
bot.run(TOKEN).
@sick birch
We need the actual error
ok
That's only a part of it
!paste
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.
Oh Swetify. Hi there!
Hi my friend! 👋👋
Shard ID None is requesting privileged intents that have not been explicitly enabled in the developer portal. It is recommended to go to https://discord.com/developers/applications/ and explicitly enable the privileged intents within your application's page. If this is not possible, then consider disabling the privileged intents instead.
The error says everything
what should i enable in portal?
You need to enable members and presence intent from discord dev portal
ok ty
Even if u ain't doing it, turning them both on won't really hurt haha
hi, im trying to make a command that checks if the last time a user was ping was at least 1 hour ago, how could i do this?
But if your bot is in high-traffic guilds probably best to leave them off to reduce computational power

@slate swan it also works by making an instance of the class (just saying)
on_message, if the message contains a ping for a user, store that time as a bot var or a cog var or something like that
thanks!
How does it increase computational power?
alright
discord.Intents.all() is a class method iirc
Yups
More events dispatched to you through the websocket, more info to process
!paste
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.
Same with Intents.default
But you don't have the intent enabled in code, just the portal, this increases it?
https://paste.pythondiscord.com/bonamaxehi @sick birch , whats this? 🙂
What is like command description for?
That's why limiting intents to exactly what you need is the best practice to follow in production
iirc it's for default help command
Can you post the code? Also that doesn't look like a full traceback
Also, once yr bot gets verified, the other intents get disabled automatically
Sure put it in a pastebin
Okay
I think on_guild_join
!d discord.on_guild_join
discord.on_guild_join(guild)```
Called when a [`Guild`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild "discord.Guild") is either created by the [`Client`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client "discord.Client") or when the [`Client`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client "discord.Client") joins a guild.
This requires [`Intents.guilds`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.guilds "discord.Intents.guilds") to be enabled.
no way i pulled that off the top of my head
That's generaly avoided though
Can iu send it in your PM @sick birch `?
My dms are closed sorry, it's better to ask here anyway
This just feels soo satisfying 
They won't
Ok
Indeed
Rip my eyes light mode
Is the bot in the server you're doing guild_ids? @kind cargo
Yep
Can you double check?
Yes
Looks like it's a slash command problem
I think
Does your bot have the necessary permissions? e.g can add application commands
Yea
You're 100% sure? You checked the box when generating the URL?
Also I'd suggest passing in change_presence in bot construction, instead of making api call on_ready
I wish this was pinned
if you kick the bot then invite it again does that work?
and i check the slash command
Regen a URL including the application command premission
Okay
Make a task and start it to change the presence repeatedly 😄
!d discord.ext.commands.Bot the kwarg here
class discord.ext.commands.Bot(command_prefix, help_command=<default-help-command>, description=None, **options)```
Represents a discord bot.
This class is a subclass of [`discord.Client`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client "discord.Client") and as a result anything that you can do with a [`discord.Client`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client "discord.Client") you can do with this bot.
This class also subclasses [`GroupMixin`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.GroupMixin "discord.ext.commands.GroupMixin") to provide the functionality to manage commands.
How to do a loop?
ty so much for the help @sick birch ❤️ keep doing the things you doing! Amazing
Like a command task loob?
I don't see the command when I do /
What do you mean command loop
Like the Bot does something I want every 10 seconds for example
Thamks
@sick birch i got one more erorr.
Yes?
!paste
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.
https://paste.pythondiscord.com/anisuquwon @sick birch
Mind showing the code?
U should do interaction.defer first. It's totally random acc to me and is fixed by doing inter.defer for me
are you talking to me? 🙂
yes
Yup
this can happen if you take too long to respond to the interaction iirc
okay
the default time you have to respond is three seconds but if you do defer you get 15 minutes
Oh damn
I believe it is await inter.response.defer()
but where should i type it?
the first line in the command, i guess
why aren't you passing in any kwargs? msg = await interaction.original_message()
what i dont really understand
@maiden fable
where should i paste "interaction.defer"
if you want to use interactions i suggest moving out of discord.py and perhaps using disnake
ok
i told you that above
so first in the whole code?
Does anyone know why my bot sends the message several times and how I fix this?
Can somebody help?
I tried disnake.SlashCommand too
(ignore caps, not sure how i did it in the code)
@spring flax
yes?
i dont know where to place it what line tell me, https://pastebin.com/raw/egdVLEkL
or above where
i honestly have no idea how discord slash commands are
@bot.slash_command(
name = "swish" ,
usage="/swish" ,
description = "Command for making payment" ,
guild_ids=GUILD_IDS ,
default_permission = False
)
@permissions.has_role("Tillgång")
async def swish(ctx:discord.ApplicationContext , namn: str, nummer: str , belopp: str):
interaction = await ctx.respond(f"Processing payment request from {ctx.author.mention} to {namn}. Amount: {belopp}.....")
msg = await interaction.original_message()
payment = utils.Payment(namn,nummer,belopp,msg.created_at,msg.id)
await msg.channel.send(file = discord.File(fp=payment.mp4))
payment.close()
This makes it look like two seperate functions
Okay....
What module are you using?
not my code
This looks very weird
yes, that's what i thought
it's discord.py
yeah like i said before i don't know if you saw this but discord.py's development has been stopped so maybe consider switching libs disnake may be the best move because of how similar it is
Do you guys prefer channel perms or guild perms for moderation commands?
Can somebody help me? My slash commands aren't working. Im new to slash commands anyways.
you have to return it
just put return on the same line as the await
oh yeah
saves a line of code
yes#
<:emojiname:emoji_id>
yes ive tried that
Mh i've put return after that but it still spam it
yeah i think it is
show code
So I can use @commands.guild_only() for commands.
But how do I disable events in Dms
!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.
@bot.event
async def on_member_update(before, after):
if str(after.status) == "online" and after.id == 628201511259865107:
channel = bot.get_channel (941209391917568000)
await channel.send("IDK")
return
do return await channel.send("idk")
zany way i can ix it?
Is there anything particular broken about this command? I can't seem to get it to work without providing a channel even tho I have a check for channel being nonepy @checks.is_admin() @commands.command(description = "Make me say something.", usage = "echo [channel] <message>", hidden = False) async def echo(self, ctx, channel: Optional[discord.TextChannel] = None, *, content: str): channel = ctx.channel if channel is None else channel await ctx.message.delete() await channel.send(content, allowed_mentions = discord.AllowedMentions(everyone = False))
It doesn't pop up when I use /, help please.
The bot still spamming
Can someone help?
- do you have the application commands scope
- you have to wait 1hour for slash commands to register globally
- if you dont want the commands to register globally use the
test_guildskwarg in the bot constructor
@slate swan im lost
dont worrie
wdym by the first one
when you invite your bot it has certain scopes you must have application commands scope on
try putting return outside the if statement
why return the method if theres nothing else to execute?
I have admin perms..
it doesn't matter its a scope bro
what should I enable
with the intents and prefix?
yea
applications.commands
bot and applications.commands scopes
Without return the bot also spamming the message
then theirs something thats causing a loop is that all of your event?
Yes
btw is that your id?
Yes? why ask that?
I did both, @slate swan @left crater, invited the bot again with scopes, added this "client = commands.Bot(command_prefix='p!', intents=intents, test_guilds=[948245926290538506])" but still I doesn't see the command when I do /?
just making sure
Here is the command code again.
can i see your whole code?
maybe its about intents?
the msg wasnt for you and no
Oh okay. So can you help please..
I don't know whats wrong. Been trying for over a hour.
slash commands dont have context lmao
wdym context lmao?
ctx?

ctx means context
I mean that depends. Some libraries have SlashContext.
await ctx.channel.edit(slowmode_delay=seconds)
await ctx.send(f"Set the slowmode in this channel to {seconds} seconds!")

just help me for god shake why nobody knows whats wrong
i've been trying for more than a hour
what lib
disnake?
Does anyone know how I can fix that the bot spams the message?
@bot.event
async def on_member_update(before, after):
if str(after.status) == "online" and after.id == 628201511259865107:
channel = bot.get_channel (941209391917568000)
await channel.send("idk")
How do I make something like variable, so person can type !setchannel "CHANNEL ID" and then later I can use that channel for like logging or shit
just make an argument that takes a text channel obj and just get the channel to log stuff or use a db to log a history
yep
Can you help me with that? How so.
how to use external emoji in embed ???
Use the emoji ID like this for example !CH_DanceBoi
Is this the correct way to fetch a channel?py announcements = await self.bot.fetch_channel(data[31])bc I keep getting this error even tho the column that data is calling has a channel ID in it
I think I just used await bot.get_channel(Channel ID)
like are you wanting it to send in a certain channel that you're in or just get it to send in a channel that's been chosen?
horrible explanation on my end
is this normal ?
Is the bot in the server which has that custom emoji?
yes
donkey is the emoji in a title?
Can you show the raw string?
its in a field title
embed.add_field(name=f" :usercoin: User Coins", value=f"{user_coins}", inline=True)```
emojis and mentions can't be in any titles
They should work in feild titles, they do for me at least
they don't for me
I want it to send the msg in a specific channel, The ID f which is stored in my db
TapRo already explain what you should use #discord-bots message
it format automatically
How do I set it so player can set an argument (example: !channelset ID) and then later, when I code something, I can use that argument for let's say example logging channel?
here is real string, sorry i cannot change @cloud dawn

when i type that it change automaticlly
Let me go try use a custom emoji in a feild title
Pass an arg inside the function, you would also need a database.
ah shit, check the documents im not the best when it comes to things like that
How can I make it?
get the channel then send it to that specific channel.
Does anyone know how I can fix that the bot spams the message?
@bot.event
async def on_member_update(before, after):
if str(after.status) == "online" and after.id == MYID:
channel = bot.get_channel (941209391917568000)
await channel.send("idk")
It works for me, just tried
What do you got so far?
this in a field title so idk why not me work
Sadly, nothing. I got the kick and logging system from the private bot, but now I need to set it to work as public.
Well compare if the before status was online to not trigger it when it was already set as online.
lemme try on mine rq
@bot.event
async def on_member_update(before, after):
if all([
before.status != after.status,
after.status == "online",
after.id == MYID
])
channel = bot.get_channel (941209391917568000)
await channel.send("idk")
The -ping is a feild title and that's a custom peepo emoji and works for me
Did you construct a database yet?
The emoji that you're trying to show, is it in the same server as the server you're using the bot in?
Nope. Didn't worked with databases yet.
no
learnt something new today, thought it was author and fields you can't put it in (besides the value of the field obviously)
That's probably it
it cannot used external emoji?
Footers too, you can't have custom emojis there either
That's the only reason I can think of as to why it isn't working for you
OMG i found the solution
You'll need it if you want to have multiple guilds work with the same command. The bot needs to know to what server you are going to send it to.
Okay, can you help me with it please?
How do I make it?
I can give you recommendations for databases but you would need to make it yourself. I can give the names of the tools as well.
You need to pay or some?
Whenever I run a bot it says: Interaction has already been acknowledged. & This command has just been synced. although I have set test_guilds in the main file, which shouldn't make them global.
Big bots -> PostgeSQL + asyncpg
Small bots -> SQLite + aiosqlite
Json based syntax -> MongoDB + Motor
No, were here to help people and solve problems, not to code entire database structures/ bots
No no, I meant like do you need to pay for it lol
for databases, Im new to it 😂
No, databases are free, you do need to host it though, sqlite is file based so that doesn't have any hosting. As for postgre or mongodb you could host them but you could also host it locally on your VPS.
This is what I currently have, basically, I need it so this ID can be changed with command.
I heard some people do it without databases tho..?
just have a argument as an int if you want to save it a dict ig
And that is only possible with a database or forcing people to have specific channel names.
Yeah that would be channel names, but i don't recommend doing that.
Sure, that would be great too. I can do that (the specific channel names).
I've try it but now i get a the SyntaxError: invalid syntax
I mean, my bot is kind of this.. protection bots things. So one "protect-logs" or smth like that channel wouldn't be bad.
So how can I do that for example?
Do you got the full error?
to get a channel with that name
how do i make If Else statements in a command? they dont seem to work for me / i dont know how to do it
a command is like any method?
You would need to check if there is a channel with that name, if not create it. Once you have a channel with that name send it there and break the loop to avoid people trying to break your bot.
Could you provide some code?
That the is full log
code, fname = _get_code_from_file(run_name, path_name)
File "C:Programs\Python\Python39\lib\runpy.py", line 242, in _get_code_from_file
code = compile(f.read(), fname, 'exec')
File "c:\bot.py", line 339
])
^
SyntaxError: invalid syntax
Yeah but doesn't getting the channel fail if the channels not in the cache? And chances are the channels not going to be in the cache
this is horrible code but this is my attempt to do it inside a command
if moderator == "1":
real_moderator = "Moderator"
elif moderator == "2":
real_moderator = "Elder Moderator"
else:
real_moderator = False```
and then i try to display ```real_moderator``` in an embed
i feel like im doing something wrong, any help ?
Could you paste your code here? Looks like the syntax error occurs after that.
Fetch it.. like i said i don't recommend this option. But if the person i'm helping doesn't want to have any database i can only provide alternatives.
How should I set it?
Could you show the whole command, i'll try and clean it up a bit.
the error is with the brackets ig
Put an : at the end of ])
enjoy my horrible, bodged, raw code https://paste.pythondiscord.com/fixepadugo
What do you mean set it?
If statements need a : at the end.
Basically, so that bot makes a channel with the name upon joining - with setting a permissions (so only like admins can see it?) and it uses that channel for the logging purposes.
I'll try to make it a bit more readable.
you do you, it is not needed to do that
@cloud dawn
!d discord.CategoryChannel.create_text_channel
await create_text_channel(name, **options)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
A shortcut method to [`Guild.create_text_channel()`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild.create_text_channel "discord.Guild.create_text_channel") to create a [`TextChannel`](https://discordpy.readthedocs.io/en/master/api.html#discord.TextChannel "discord.TextChannel") in the category.
Does somebody have a idea, why my slash commands disappear after using one
I know i was a little bit brain afk im sorry
Do you have an idea why it happends?
No.
Thanks man. And how do I use it now as an ID?
Wouldn't be asking then @cloud dawn
What should I put in the brackets of "getchannel"
Is there a reason why it doesn't work? Do you get an error?
Okay i tryed it but i dont get an error or something but the bot do nothing
it does not raise an error, but when someone has Moderator to 1 , it pastes as False, it seems my if else is not working
I understand, but i want to isolate the issue, do all commands have this? If so you maby have an specific on_application_command events?
could it be that you converted it
Is that not what you wanted? To stop it from spamming?
what do you mean exactly
Yes but i wanted that the bot send the message one time
Are you sure the moderator 1 isn't an int?
I see, moderator is this
moderator = response.json()["moderator"]
Why does it say command not found?
@bot.command()
async def abc(ctx):
if ctx.author_id == 700061502089986139:
discord.Member.add_roles(ctx.authot_id, 906166247497027645, reason=None, atomic=True)
await ctx.send("Успешно")
else:
await ctx.send("Не доступно")```
oops it is an int
wow im stupid wtf
this is bad
how to add author_id
like !add @tacit horizon
- replace discord.Member with an instance of it
- it's ctx.author.id, not ctx.author_id and not ctx.authot_id
- you do not need reason and atomic in your add_roles()
- your 906166247497027645 has to be a role object, not the id
- you don't have a member argument in add_roles
Not sure what you want exactly since the reason it spams is because you were already online then it will check it again on every member change.
Guys rate my bot
@client.event
async def on_guild_join(guild):
await guild.leave()
10/10
100/10
Ayyyyy tysm
All commands are ready to use after I start the bot. As soon as I use one slash command, then all of my slash commands disappear (unavailable to use). Interesting part is that, all of those things worked before, but now suddenly these don't. I even commented out all of my existing commands and created simple ping command, but it still disappears after using it.
@client.command(pass_context = True)
async def add(ctx,user : discord.Member):
```how to get the member id from there
and please remove pass_context
ok
unless you use dpy v1
You are addressing every issue, and not even telling him his actual issue. Keep the comments to yourself if you are just going to insult starter coders.
Do any other commands have this issue?
Okay I want that the bot send a message one time into a channel when a specific user comes online but i dont know how i can disable the loop
Do you register them globally or using a testing mode?
It's different for Disnake?
I register these using a testing mode.
afaik not.
Even if I register them globally, they shouldn't appear in the first place (for atleast 1 hour)
😕 I have a database, that's what my data variable is containing. I'm expecting this command to be used very infrequently which is why I don't think the channel will be in the cache.
Could you show how you register them and how you construct the bot?
..
Didn't my code help with that? Since we're now only checking if the user was not already online + your additions.
example code:)
I'm assuming you got the command prefix for debug commands. Do those work?
No when i try this code the bot dont send a message
But you just copy pasted the method..?
Positive
can i put emojis in Author Name ?
Huh? :-;
Okay let's grab the old code then.. ```py
@bot.event
async def on_member_update(before, after):
if str(after.status) == "online" and after.id == MYID:
channel = bot.get_channel (941209391917568000)
await channel.send("idk")
Is there a any chance that I've been testing the slash commands too much, thus getting rate limited? if so it still should give an error message..
can i put custom emojis in Author Name ?
I meant that you literally copied await create_text_channel(name, **options) from the embed
Kind of-?
That's not how it works 😅
what do you exactly mean? like in discord?
yes
embed
sorry real question is can i put custom emoji in embed area named Author Name
well if you just use ctx.author.name and then pass a custom emoji to the string
you can get an emoji with
Because the event check always whether the user is online ig
if moderator == 1:
real_moderator = f" {username}"
elif moderator == 2:
real_moderator = f" {username}"
else:
real_moderator = f"{username}"
name = real_moderator```
there I have to check...
!d discord.Guild.create_text_channel does this method make more sense?
await create_text_channel(name, *, reason=None, category=None, position=..., topic=..., slowmode_delay=..., nsfw=..., overwrites=...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Creates a [`TextChannel`](https://discordpy.readthedocs.io/en/master/api.html#discord.TextChannel "discord.TextChannel") for the guild.
Note that you need the [`manage_channels`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.manage_channels "discord.Permissions.manage_channels") permission to create the channel.
The `overwrites` parameter can be used to create a ‘secret’ channel upon creation. This parameter expects a [`dict`](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.9)") of overwrites with the target (either a [`Member`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member "discord.Member") or a [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role")) as the key and a [`PermissionOverwrite`](https://discordpy.readthedocs.io/en/master/api.html#discord.PermissionOverwrite "discord.PermissionOverwrite") as the value.
Note
Creating a channel of a specified position will not update the position of other channels to follow suit. A follow-up call to [`edit()`](https://discordpy.readthedocs.io/en/master/api.html#discord.TextChannel.edit "discord.TextChannel.edit") will be required to update the position of the channel in the channel list...
@sick birch can u help me>?
ig that should work though
This only triggers if something changes inside the members profile. So i have no clue on why it would be "spamming" in your regard.
Yep.
how do i make commands case insensitive
example: TEST!test and test!TEST are the same
!d discord.ext.commands.Bot.case_insensitive
Whether the commands should be case insensitive. Defaults to False. This attribute does not carry over to groups. You must set it to every group if you require group commands to be case insensitive as well.
First :p
:C
You're not the only one having the api docs on speed dial.
😆
🧠 💪 ⌨️ when
be big brain
Are you using 3 monitors?
client having get_emoji but not guild
Yes :3
Ohh damn that's cool
noob stuff, I only double check with the API
The res of this picture is insane lol 6560x2560
*6
xD
is it possible to have same callback function for multiple buttons after subclassing ui View
my monitors are not lined up
You got 6?
Don't tell me u sit surrounded by 6 monitors
figure it out then
I would need a second graphics card lol
interaction = await ctx.respond(f"Bearbetar betalningsbegäran från {ctx.author.mention} to {namn}. Amount: {belopp}.....")```
Anyone help me with this?
I have a question does the mouse cursor casually move across one screen and enter the other?
yep sorry wait
Yeah, otherwise it would be kind of pointless lol
is it possible to have same callback function for multiple buttons after subclassing ui View
panda
meh
the guy I critisized vanished
😆 that means u need high sensitivity or a really long mouse pad
No shite i would leave aswell lol
!paste
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.
i use 1600-2200dpi mostly 1800
O
mind showing the whole command?
That's not that high right?
like the whole code?
ctx don't even have respond
oh cuz it's ApplicationContext
yea
well I have no idea what that has
Okay
that's from the 3rd party library, right?
yeah that was a dumb question
try replacing respond with reply and see what happens
I strongly doubt ApplicationContext doesn't inherit from Context
error?
error handler?
Variable names should be in snake_case, not camelCase
Your variables are written in camelCase, they should be snake_case
async def on_member_join(member):
embed = discord.Embed(colour=0x7fd364, description=f"ברוכים הבאים לשרת ScarLor {len(list(member.guild.members))} member!")
embed.set_thumbnail(url=f"{member.avatar_url}")
embed.set_author(name=f"{member.name}", icon_url=f"{member.avatar_url}")
embed.set_footer(text=f"{member.guild}", icon_url=f"{member.guild.icon_url}")
embed.timestamp = datetime.datetime.utcnow()
embed.add_field(name="ID:", value=member.id)
embed.add_field(name="Guild name:", value=member.display_name)
embed.add_field(name="Created at:", value=member.created_at.strftime("%a, %#d %B %Y, %I:%M %p UTC"))
embed.add_field(name="Joined at:", value=member.joined_at.strftime("%a, %#d %B %Y, %I:%M %p UTC"))
channel = client.get_channel(id=948215514734424064)
await channel.send(embed=embed)
role = get(member.guild.roles, name="Member")
await member.add_roles(role)```
any one can help me fix that
well member is a required arg that is missing
run
.avatar @slate swan
with the ping
!paste
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.
and there is an error, why you noping
that's what your code is
be honest
did you copy that code

try
await ctx.send(ctx.author.avatar)
In the .send() do embed=embed_obj
instead of "avatar"
update dpy
pip install github link which I never remember
that installs stable
that's 1.7
master is 2.0, which isn't on pip
Hey I need some help , it is not a Discord bot but it is a telegram bot
I dont know if it counts
type discord.py 2.0 github in google
no
where can I ask for help then?
whats a telegram bot
pip install - U git+https://github.com/Rapptz/discord.py
It is a bot but it works in telegram
@slate swan
well maybe claim a help channel
yes
don't matter
well maybe if your pip is 3.6
you might wanna specify that you wanna install it with the right python version
that's above 3.8
remove the space between - and U
phone messes with me, Imma throw it out the window
ey, that's not the dpy installation, me got nothing to do with that

cannot find command git
why do you need it anyways
pip install -U git+https://github.com/Rapptz/discord.py
git command
pip install -U git+https://github.com/Rapptz/discord.py
now me wondering what the -U is for
pip install git+https://github.com/Rapptz/discord.py
oh it's update, I'm dumb
me too
caeden help
you need git cli installed so that it can retrieve the files from the github
so go install github cli @slate swan
alr
watch a 5 minute youtube video about what it is while youre at it
if its installed then the pip install should work
well not really
you want to install the 2.0
so you would need to specify that
I'm tryna make a welcome command inn disnake but it doesnt work
@InteractionBot.event
async def on_member_join(self):
"""Fires off a welcome message on user join."""
welcomeEmbed = disnake.Embed(
title = f"Welcome!",
description = "Shitter >:)"
)
await inter.response.send_message(embed = welcomeEmbed)
just install disnake instead
now use disnake instead of discord
if you need a guide for using disnake, they have a written guide over at https://guide.disnake.dev btw
dictionary for python3?
w h || a || t
!d dictionary
can anyone much abt slash commands
lol
somebody that can slash commands can you help.
yes
well all you need to do is replace disnake with discord
import discord disnake
embed = discorddisnake.Embed
get what im doing? replace discord with disnake
?
can I suggest learning python taking a break?
what is the best way to make bot 24/7 online? is there a web page that can you suggest?
Rent a vps or self host
The cool thing is, these bots will run on literally anything
if there would be a web page domain? can i do that?
Go on lowendbox and look at $1 per month vps
There’s one for $10 a year and they accept crypto if you don’t have PayPal or cc
🤷♂️
Anything works
Hey guys, so about this line.
channel = client.get_channel(801446246954827808)
await channel.send(f"{member} has been **banned** by {ctx.author} for **{reason}**!")
Since I'm making it a public bot, how can I made it so it gets the channel by it's name, not the ID?
This is in the ban event handler? Look at the docs
The object that that’s called with includes a reference to guild
Yes, it is.
?
I just need it so it takes the channel with the name I typed, not the ID.
How do I do that?
channel = client.get_channel(name=?)
Or? Something like that.
No man, it doesn't have to do anything with ban. Ignore the other lane
You can’t do that, unfortunately
I just need this lane
I can.. I just don't know how bruh
you can get the channel, if not, create one
Loop through all the channels in the guild and check if it exists
Exactly. How?
How can i stop that the bot spam the message into the channel?
@bot.event
async def on_member_update(before, after):
if str(after.status) == "online" and after.id == MYID:
channel = bot.get_channel (941209391917568000)
await channel.send("idk")
pass
Well, you need a reference to the guild in the first place. That comes from the ban event
you can use utils.get to iternate through all the channels in the guild using the channel name
!d disnake.utils.get
disnake.utils.get(iterable, **attrs)```
A helper that returns the first element in the iterable that meets all the traits passed in `attrs`. This is an alternative for [`find()`](https://docs.disnake.dev/en/latest/api.html#disnake.utils.find "disnake.utils.find").
When multiple attributes are specified, they are checked using logical AND, not logical OR. Meaning they have to meet every attribute passed in and not one of them.
To have a nested attribute search (i.e. search by `x.y`) then pass in `x__y` as the keyword argument.
If nothing is found that matches the attributes passed, then `None` is returned.
Examples
Basic usage...
Where should I use it, and how? Not sure.
What should I put instead of
"channel = client.get_channel(name=?)"
take a look at this link
Yeah, or just for channel in guild.channels: if channel.name == … and isinstance(channel, TextChannel):
thats useless when you have utils.get
That’s why I said or. It might be more expressive, but either way it’s an alternative
lol
get(guild.channels, name=“channel name”) if I’m not mistaken
Attrs are kwargs
you literally did the same thing for muted_role
I didn't know you can do same for the channels?
How can i stop that the bot spam the message into the channel?
@bot.event
async def on_member_update(before, after):
if str(after.status) == "online" and after.id == MYID:
channel = bot.get_channel (941209391917568000)
await channel.send("idk")
pass
i told you to read the docs for it?
it has what you need?
how do i make it so
if it reaches else, make it like do nothing and continue the thing
instead of return do pass
discord.utils.get 👀
discord.utils.get(iterable, **attrs)```
A helper that returns the first element in the iterable that meets all the traits passed in `attrs`. This is an alternative for [`find()`](https://discordpy.readthedocs.io/en/master/api.html#discord.utils.find "discord.utils.find").
When multiple attributes are specified, they are checked using logical AND, not logical OR. Meaning they have to meet every attribute passed in and not one of them.
To have a nested attribute search (i.e. search by `x.y`) then pass in `x__y` as the keyword argument.
If nothing is found that matches the attributes passed, then `None` is returned.
Examples
Basic usage...
pass guild.channels as the first arg, name="blabla" as the kwarg
why doesnt my emoji work in Author Name?
it doesn't work for me in any
not embed, the normal ctx
it doesn't work
How can i stop that the bot spam the message into the channel?
@bot.event
async def on_member_update(before, after):
if str(after.status) == "online" and after.id == MYID:
channel = bot.get_channel (941209391917568000)
await channel.send("idk")
pass
iirc can't do it in embed titles
:( ok
Can you have nultiple task.loop
Yes
@final iron
Why is my tasks.loop not working
If I paste my code into my first tasks.loop it works
Not the second
Oh im dumb
I don't understand what you're doing
I have to start the task
those are just temporary
fellow pep8 compliance officer *salutes*
variableName
I meant for the "elif" statements
Why
Cringe
Hey @void elm!
It looks like you tried to attach file type(s) that we do not allow (.zip). We currently allow the following file types: .gif, .jpg, .jpeg, .mov, .mp4, .mpg, .png, .mp3, .wav, .ogg, .webm, .webp, .flac, .m4a, .csv, .json.
Feel free to ask in #community-meta if you think this is a mistake.
I'm still super confused
What's the best way to create reminders in Discord?
I thought about storing each reminder in json...
Don't use json
Yeah, that's why im asking a better method
Use a database
reminder id?
yes, generate a random UUID
is there a better way than
if True:
return
elif True:
return
...ect
if True: will always execute so you can get rid of the whole thing
These 2 are equivalent:
if True:
print("Hello, world")
vs
print("Hello, world")
Oh I see
run command files but yes
I should also create a column for reminder content, no?
but what is UUID for
To identify a reminder
Fetch it by ID rather than name
Alr ill try that thanks
@sick birch its still nonr
Can we see the updated code?
Yea
How can i stop that the bot spam the message into the channel?
@bot.event
async def on_member_update(before, after):
if str(after.status) == "online" and after.id == MYID:
channel = bot.get_channel (941209391917568000)
await channel.send("idk")
pass
Why not just guild.get_channel(id) or await guild.fetch_channel(id)
That way you're getting from the internal cache
Oh ok
yo TypeError: '<' not supported between instances of 'float' and 'datetime.datetime' the code is py if str(payload.emoji) == str(Giveaway_Items[i]['Emoji']) and time.time() < datetime.datetime.fromisoformat(e_time):
not sure why i get the error
time.time() < datetime.datetime.fromisoformat(e_time)
You're comparing 2 different objects
time.time isn't a date time object?
.
How can i stop that the bot spam the message into the channel?
I tryed that the bot send a message to an channel if a specific person comes online. But if the person comes online the bot spam the message permanently.
@bot.event
async def on_member_update(before, after):
if str(after.status) == "online" and after.id == MYID:
channel = bot.get_channel (941209391917568000)
await channel.send("idk")
pass
You're comparing a float to a datetime.datetime object
You can't compare primitive datatypes to objects
You need to figure out what common format makes the most sense for your specific use-case
?now = datetime.datetime.now()
That also returns a datetime object
But if you replace time.time() with datetime.datetime.now() you should be able to compare them
(I think, I haven't worked with the datetime library all that much)
How can I add the bottom part to my embeds?
embed.set_footer(...)
Yes but how did they do the logo and time?
!d discord.Embed.set_footer
set_footer(*, text=Embed.Empty, icon_url=Embed.Empty)```
Sets the footer for the embed content.
This function returns the class instance to allow for fluent-style chaining.
O
like a so
And the time?
how can i send a file in an embed?
Nothing special about the time, it's just text
!local-file
Thanks to discord.py, sending local files as embed images is simple. You have to create an instance of discord.File class:
# When you know the file exact path, you can pass it.
file = discord.File("/this/is/path/to/my/file.png", filename="file.png")
# When you have the file-like object, then you can pass this instead path.
with open("/this/is/path/to/my/file.png", "rb") as f:
file = discord.File(f)
When using the file-like object, you have to open it in rb mode. Also, in this case, passing filename to it is not necessary.
Please note that filename can't contain underscores. This is a Discord limitation.
discord.Embed instances have a set_image method which can be used to set an attachment as an image:
embed = discord.Embed()
# Set other fields
embed.set_image(url="attachment://file.png") # Filename here must be exactly same as attachment filename.
After this, you can send an embed with an attachment to Discord:
await channel.send(file=file, embed=embed)
This example uses discord.TextChannel for sending, but any instance of discord.abc.Messageable can be used for sending.
thanks
Ik but that shows the time in my local time. It shows a different time for different users. But when I try it, it just shows the utc time or a bunch of numbers
Timestamp
Hm I'm not sure if discord timestamps are valid at the footer
I’ve tried that too, but I can’t get it to work
what if i want to send files at random
Well, any errors?
Yes, but it’s been a while so I don’t remember them
You'd do the same thing as you would normally, except probably use f-strings to change the names of the files etc
what do i put for filename?
The name of the file
Pick the one you want to send
Oh i just saw you want random
If that's in a JSON you can load it and random.choice()
if not you can get all the files in a folder (one containing all of your images) and random.choice() that too
what do i put for filename?
Use os.listdir() to get a list of all files in a folder
ok
In your case get all the files in your nft folder
Or since it looks like you have all the files neatly arranged,
f"\path\to\nft\folder\images{random.choice(range(60))}.jpg"
but i want it to send in an embed
Use this to construct a discord.File object from the path name
Is there any way I test my kick command? I don't have anyone to test it on
Alright brb. The library I'm using doest have tutorials on it and I'm not very good at documentation understanding
@sick birch files = discord.File(f"C:\Users\nikit\Downloads\nft\images{randnum}", filename=f"image{randnum}.jpg") nfts_Emb.set_image(url=) i did this and i have no clue what to put for the url
attachment://image.png
wdym by attachment?
Or the name of the file you're going to send
attachment://<filename>
It would be easier if you just did
files = discord.File(..., filename="image.jpg")
Also make sure you include the .jpg at the end of the f string
oh yeah
class Commands(commands.Cog):
def __init__(self, bot):
self.bot = bot
def get_quote():
response = requests.get("https://zenquotes.io/api/random")
json_data = json.loads(response.text)
quote = json_data[0]['q'] + " - " + json_data[0]['a']
return(quote)
@commands.Cog.listener()
async def on_message(self, bot, message):
if message.author == bot.user:
return
await bot.process_commands(message)
@commands.command()
async def help(self, ctx):
embed = discord.Embed(
title=f"Commands",
description=f"""
>help (shows this command)
>quote
>hello
>cmds
>tictactoe (mention) (mention)
>slap (mention)
>cf (coinflip)
>rule (1-4)
""",
# embed.set_thumbnail("./tmgmidvitelogonowords.png", url)
colour=0xffffff)
await ctx.send(embed=embed)
def setup(bot):
bot.add_cog(Commands(bot))```
cog file ^^
```py
@bot.event
async def on_ready():
bot.load_extension("cogs.maincommands")
bot.load_extension("cogs.status")```
main file ^^
Why are my commands not defined?
oh no. loading cogs in on ready
why return(quote)
Few things to point out:
- don't load extensions
on_ready - filenames should be snake_cased
- subclass
HelpCommand
just some things to point out but the actual issue isn't with any of those
that's just the function for getting the quote from the api
Requests isn't async
2.
Why are you listening for an on_message event then doing nothing
3.
on_message doesn't take bot
4.
Don't create a custom help command, just subclass it
but why (quote)? just do return quote?
why use docstrings and not \n lol
useless () tbh
thats what im saying
loll
You don't have to process_commands() within a listener, and I'm pretty sure listeners don't pick up your own messages anyway
Perhaps a javascript developer
The funniest part is we've found every issue except what they asked for 😂
i fixed the problems
That was fast
which issue out of all of them
Can we see the new & updated code?
None, their issue was why the extension wasn't being loaded
I'm guessing that's a direct result of all the other issues
¯_(ツ)_/¯
someone come to ot channel
why
got question about js/ts
is 4 optional?
@sick birch
you don't have to subclass help command, but its recommended
sure what's up
Yes but it's highly recommend
random module
Just pick a random number between 1-100, add % to the end of it
so i wanna be a backend developer mainly and I think I'm going to focus mostly on backend dev with rust and c#. But, I know I probably should learn JS in the process (which I already know some JS). I just wanted to know if the difference between TS and JS is that big to warrant me using TS over JS
I would say always use TS over JS, there's really no reason not to
yeah thats what i thought
What's the difference between js and ts?
yeah and use .randint
type system
TS is strongly typed, i.e you can do types like so:
const someVariable: string = "Hello, world!";
?
Also generics, and a lot of other features
random.randint()
Let's not take away from the channel topic, I think if you all want to discuss this further I would be more than happy to in one of the OT channels
TS should be relatively easy since I know some c# and rust, right? And I should also learn JS before TS?
u need to fill the ()
!e
print(__import__("random").randint(0, 100))
@slate swan :white_check_mark: Your eval job has completed with return code 0.
50
yeah
really need to add the start😔
my commands still aren't defined
smh this isn't Javascript
we don't add characters
str() and add
class Commands(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.command()
async def help(self, ctx):
embed = discord.Embed(
title=f"Commands",
description=f"""
>help (shows this command)
>quote
>hello
>cmds
>tictactoe (mention) (mention)
>tmg
>slap (mention)
>cf (coinflip)
>rule (1-4)
""",
# embed.set_thumbnail("./tmgmidvitelogonowords.png", url)
colour=0xffffff)
await ctx.send(embed=embed)```
cog file ^^
```py
@bot.event
async def on_ready():
bot.load_extension("cogs.maincommands")
bot.load_extension("cogs.status")```
main file ^^
error?
discord.ext.commands.errors.CommandNotFound: Command "help" is not found```
useless f string and why doc strings and not \n
i prefer it laid out and f strings will come in use later on
sooo, my actual problem?
docstrings are laid out
ik but i prefer it laid out in the code so i have an idea of what it will look like
so can someone tell me why it isn't defined
did you add the cog
@slate swan :x: Your eval job has completed with return code 1.
001 | File "<string>", line 3
002 | import discord.ext import commands
003 | ^^^^^^
004 | SyntaxError: invalid syntax
^
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape```
what
can someone tell me why my commands aren't defined?
Put an r before the string
oh
Define commands
so do i use format to get the random thing
;-;
Nice job leaking your token
oops
bro ur token is there
Don't name your commands.Bot instance client
can u elaborate
Name it bot
If you don't know how to define something dpy really isn't for you
then/
You'll have an extremely hard time without any prior python knowledge
i know how to define stuff, it's already defined, can u tell me how to define the error i'm having
Function names should be in snake_case, not camelCase
sir why are u using replit
me well
No
cause im on my school laptop and specs r garbage
like all school laptops r
¯_(ツ)_/¯
did u see the code i sent
thats fair

