#discord-bots
1 messages · Page 141 of 1
All about preference, personally I use nextcord a lot of people use discord py though
Is there a way to check what channel a bot has been invited to when it joins a guild?
Nevermind! I think I've found a solution
5. Do not provide or request help on projects that may break laws, breach terms of services, or are malicious or inappropriate.
"breach terms of services"
if something works, it doesn't mean that its right thing to do
it will but if someone else got your project source they will have your bot token
try it and see
and they will do bad thing with your bot
such as sending weird pictures that we all know
my token, not my bot token
its the same
lol
What does this refer to:
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body In type: Value must be one of {4, 5, 6, 7, 10}.
I am trying to use this:
await interaction.response.send_modal(Questionnaire2(self.form_data, self.view, self.username_view, self.form_names)) inside Questionnaire2().
Where can I find the reference to all form body with their value things?
can you show us the code please?
class Questionnaire2(Modal, title = "Questionaire Response"):
def __init__(self, form_data, view, username_view, form_names):
super().__init__()
self.form_data = form_data
self.username_view = username_view
self.view = view
self.form_names = form_names
name = TextInput(label='Type a profile name here', custom_id = "form_name")
async def on_submit(self, interaction: discord.Interaction):
answer = interaction.data["components"][0]['components'][0]['value']
if answer not in self.form_names:
self.form_data[interaction.data['components'][0]['components'][0]['custom_id']] = answer
await interaction.response.send_message(view = self.view, ephemeral=True)
await self.view.wait()
self.username_view.stop()
else:
await interaction.response.send_modal(Questionnaire2(self.form_data, self.view, self.username_view, self.form_names))```
Error in the last line.
show the slash or normal command too
this code is ok from my pov
It has dozens of lines, here is the callback though:
async def newusername_callback(interaction):
print("usernames", form_names)
await interaction.response.send_modal(Questionnaire2(form_data, view, username_view, form_names))
await view.wait()
username_view.stop()```
last line is not ok tho 💀
Yeah that's where I am having an issue lol.
you can't respond to a modal, with a modal
It's not that important.
it is
Oh, so my idea is that when they use an already existing name I will re-send the same modal to retry. Is there any good way to do it?
...........
send a button that sends a the modal as response
you can check for if the name that he answered is exist or not
if not u send an ephemeral message with a button retry ans send that same modal again
That's a good idea.
Yeah, that's good.
if str(self.name) == "Exist name or a list of names":
await interaction.response.send_message("This name exist already! Click the retry button below to add a new name.", view=yourretrybutton(),ephemeral=True)
@potent light like dat ;] here's an quickkk example
thanks! it worked
you're welcome.
How do I remove a button from a message?
I want to make it so when someone clicks a button the original message is edited and the button is removed
@marsh pollen :white_check_mark: Your 3.11 eval job has completed with return code 0.
['-', '-', '-', '-', '-', '-', '-', '-', '-', 's']
I believe you can just pass view=None to the edited message and the buttons will disappear.
Yeah I eventually figured it out. Thank you tho 🙂
Np
How do you pronounced ephemeral
Is it ee-FEE-mur-al
Or eh-FEE-mur-al
Or other?
Hi, I really want to hear the opinion of an experienced programmer on my code. I don't have anyone near me that could do that, but I couldn't find anywhere in the rules that I am not allowed to do this in the help channels. Still, I thought I'd ask here first. It really isn't a big piece of code, it's just that I want to improve on it if I can.
Post it here and people will hop in to help if they can
I pronounce it eh-feh-mur-al
but it probably doesn't matter exactly how your say it :)
how make ban command i ben trying so hard
Personally I wouldn't bother with making yet another bot for commands such as banning/kicking members. The built-in options on Discord can do that perfectly fine and so can much larger, trusted bots such as Dyno. But if you really wanna go for it, Guild.ban is probably what you're after.
why are you discouraging people to make bots in a a channel meant to help people in making them. 💀
It's eifemeral
🤫 he's a discord employee
I did help them, and I apologise for coming across as discouraging, but I'm saying that if you're making a bot, try to make it unique and not do the exact same thing as thousands of other bots.
Yeah. That worked. But I need it in a slash command that's whats hard for me.
If you are using discord.py. Here is an example:
@bot.tree.command(name="slash-command-name", description="Command description")
async def slash(interaction: discord.Interaction):
await interaction.response.send_message("Hello! You used a slash command.")
yuh
i wish discord.py would do this:
@bot.tree.command(name="my-command", description="Command desc")
async def slash(ctx):
await ctx.send("hello!")
that would be so much easier
You can give discord.Interaction in any variable such as for example ctx
As slash command is positional only. you can use ctx
but as it's a response you can't do ctx.send() you have to do ctx.response.send_message()
omg
That's.... bad
i mean. it’s really not all about that. people don’t just make bots for to be conventional or practical. a lot of the time it’s really about the experience for them. sure you can just find another bot that does the same thing but there’s a sense of accomplishment in your craft when you do it yourself.
with that message i was getting pinged every second
nextcord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In options.1.choices.5.name: This field is required
what does this even mean?
the choice should have a name
k thx
it still gives the error
@bot.slash_command(guild_ids=GUILD_IDS)
async def clearinfracs(
interaction: Interaction,
user: nextcord.User = SlashOption(
required=True,
name="user",
description="The user to remove the infractions from",
),
remove=SlashOption(
required=True,
choices=str(clrinfr),
name="removeall",
description='put in "all" or 1-10 or a power of 5',
),
):
if remove == "all":
database_functions.infractions(
user_id=user, type="removeW", infrac=all, removeamount="all"
)
embedr = nextcord.Embed(
color=nextcord.Color.blurple(),
title="Alle overtredingen van {interaction.user} zijn verwijderd!",
description="Tip: je aan de regels houden werkt echt!",
)
await interaction.response.send_message(embed=embedr)
elif remove == 0:
return ValueError
elif remove == int > 0:
database_functions.infractions(
user_id=user, type="removeW", infrac=all, removeamount=remove
)
here's the code
i don;t think thats how choices argument work in SlashOption work
what do you mean?
omgggg nextcordd
how do i make my entire dropdown so that users cant interact with it once a option is clicked?
Ikr so sexy
property max_values```
The maximum number of items that can be chosen for this select menu.
Is it just me or the channel's activity has kinda died down as compared to before......?
my boy the thing you're trying to make is useless
yh
how do I make a slash option that has all members of a server as the choices?
wait i think i found out....
type hint discord.Member to the param
yeah i'm using nextcord
lol
also my code didn't work so the question is still relevant
should still be the same thing but with different module name
so like choices = nextcord.Member
type hint, not default
arg: typehint = default
o
wait I am doing this wrong for sure, it's not choices: nextcord.Member
i am really being stupid now
Imma make a casino bot
How do I correct this..
!intents
Using intents in discord.py
Intents are a feature of Discord that tells the gateway exactly which events to send your bot. Various features of discord.py rely on having particular intents enabled, further detailed in its documentation. Since discord.py v2.0.0, it has become mandatory for developers to explicitly define the values of these intents in their code.
There are standard and privileged intents. To use privileged intents like Presences, Server Members, and Message Content, you have to first enable them in the Discord Developer Portal. In there, go to the Bot page of your application, scroll down to the Privileged Gateway Intents section, and enable the privileged intents that you need. Standard intents can be used without any changes in the developer portal.
Afterwards in your code, you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:
from discord import Intents
from discord.ext import commands
# Enable all standard intents and message content
# (prefix commands generally require message content)
intents = Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix="!", intents=intents)
For more info about using intents, see discord.py's related guide, and for general information about them, see the Discord developer documentation on intents.
Hey!
I am making a discord bot and was wondering if it is possible to make like a limit to how many people can click a button
Say if 5 people click a button, after the 5th person clicks the button the button turns disabled?
Thank you!
Thank you
Add a counter state to your ui.View subclass, and in your interaction_check see if it's > 5
Do you know what I would look up to find something on how to do that?
It's always another problem after another
(this is line 43 on the bottom)
I really don't know what this means
!d discord.ui.View
class discord.ui.View(*, timeout=180.0)```
Represents a UI view.
This object must be inherited to create a UI within Discord.
New in version 2.0.
This should have all you need
Can you show us your code?
it's called bot not client
I'm not picking up what your putting down, Can you please elaborate
In the github examples page from discord.py there is a counter xample.
you probably called your bot instance "bot" (like it should be)
But a lot of tutorials will call a "bot" a "client" (which is incorrect)
you are using the Bot not Client.
This may have gotten you confused
Actually-..

This is where it starts (cant figure out how to set it as an actual copyable thing, sorry)
Just remove the lines with red underline.
Also FYI having 2 @bot.event means that the 2nd one will override the first one
So worth keeping in mind
I'm not quite sure what a listener is (I have barely scratched the surface of how to code within python so bear with me on this)
I highly recommend checking out the basics first, we're just doing it for you at this point.
This is a listener
@bot.listen()
async def on_message(message):
...
And this is an event
@bot.event
async def on_message(message):
...
what is it then?
have ya synced?
@hazy prawn there's an excellent getting started guide for you here
https://discordpy.readthedocs.io/en/stable/ext/commands/commands.html
I think you'd find it much more helpful than us :)
I am 1 error away from re-coding this bot entirely..
still won't work tho
when i click the button it does what its supposed to i still get interaction error?
how can you detect if a discord websocket connection is closed and the close code?
how did you respond?
listens for the command or specific word
!d discord.on_disconnect
discord.on_disconnect()```
Called when the client has disconnected from Discord, or a connection attempt to Discord has failed. This could happen either through the internet being disconnected, explicit calls to close, or Discord terminating the connection one way or the other.
This function can be called many times without a corresponding [`on_connect()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_connect "discord.on_connect") call.
im trying to do it with aiohttp
if you're creating your own wrapper - it might be a question for #965291516031549500
use interaction.response.send_message
ok
i dont want to reply
Then you can await interaction.response.defer() though you should reply
well then its gonna make the interaction fail then
(or you do this and make it ephemeral)
how do i use that though im having issues using it or learning how to use it
Just add it before your interaction.channel.send
await interaction.response.defer(interaction.channel.send)?
or it is literally just await interaction.response.defer() interaction.channel.send
Yes
how in the.....
Okay hear me out here. I want a SlashOption in a slash command that has all the members of the server as the options to choose from. How would i do that?
?
typehint the option.
Put a ; in between and await it.
In it's own line
await interaction.response.defer()
await interaction.channel.send("Hello, world!")
wdym?
no nvm i know what u mean, just not how to do it
async def commandyes(self, interaction: Interaction, member: Member) -> None:
Where would I find that?
i was fr confused works now ty lol
french?
the french are very confused
wot
🗿
no, fr means for real
lol

fr?
frfr
I mean french
NL?
what would i put in choices= ?
Please speak English otherwise Robin gets upset.
Sorry robin :3
No clue what library you use, you haven't told us and on top of that you didn't provide any code to indicate for us what library it is.
i am so sorry
here:
@bot.slash_command(guild_ids=GUILD_IDS)
async def clearinfracs(
interaction: Interaction,
member: Member
user:= SlashOption(
choices=member,
required=True,
description="The user to remove the infractions from",
),
remove=SlashOption(
required=True,
choices=str(clrinfr),
description='put in "all" or 1-10 or a power of 5',
),
):
if remove == "all":
database_functions.infractions(
user_id=user, type="removeW", infrac=all, removeamount="all"
)
embedr = nextcord.Embed(
color=nextcord.Color.blurple(),
title="Alle overtredingen van {interaction.user} zijn verwijderd!",
description="Tip: je aan de regels houden werkt echt!",
)
await interaction.response.send_message(embed=embedr)
elif remove == 0:
return ValueError
elif remove == int > 0:
database_functions.infractions(
user_id=user, type="removeW", infrac=all, removeamount=remove
)
ignore choices=member for now
py-cord it is
heheh
Is it py-cord?
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=None, *, reason=None):
time=convert(time)
if member == None:
await ctx.send("Please mention a member.")
return
if time == None:
await ctx.send("Please write the time!")
return
if member == ctx.author:
embed = nextcord.Embed(
color=nextcord.Colour.red(),
description="You can't mute yourself !"
)
await ctx.send(embed=embed)
return
muterole = nextcord.utils.get(ctx.guild.roles, name="Muted")
if muterole is None:
muterole = await ctx.guild.create_role(name="Muted")
for channel in ctx.guild.text_channels:
await channel.set_permissions(muterole, overwrite=nextcord.PermissionOverwrite(send_messages=False))
if muterole in member.roles:
embed = nextcord.Embed(
color=nextcord.Colour.red(),
title="Mute Error :x:",
description=f'This member is already muted!'
)
await ctx.send(embed=embed)
return
await member.add_roles(muterole)
embed = nextcord.Embed(
color=nextcord.Colour.green(),
title=' Muted',
description=f'**{member.mention}** is now muted reason: **{reason}**.'
)
embed.set_footer(text=f'Muted by {ctx.author}.')
await ctx.send(embed=embed)
await member.remove_roles(time=time)```
```nextcord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: remove_roles() got an unexpected keyword argument 'time'
@bot.slash_command(guild_ids=[TESTING_GUILD_ID])
async def hi(
interaction: Interaction,
member: nextcord.Member = SlashOption(name="user", description="User to say hi to"),
):
await interaction.response.send_message(f"{interaction.user} just said hi to {member.mention}")
``` copy pasted from their site.
I recommend using the docs and searching keyword.
l
They also have a set of examples on their git -> https://github.com/nextcord/nextcord/tree/master/examples/application_commands
thx!
Might also be making a starter tutorial for the 4 most popular packages, including resources like this 👀
In options.1.choices.5.name: This field is required
It returns this error, i have no clue,
@bot.slash_command(guild_ids=GUILD_IDS)
async def clearinfracs(
interaction: Interaction,
user: nextcord.Member = SlashOption(
name="user",
required=True,
description="The user to remove the infractions from",
),
remove=SlashOption(
required=True,
choices=str(clrinfr),
description='put in "all" or 1-10 or a power of 5',
),
):
if remove == "all":
database_functions.infractions(
user_id=user, type="removeW", infrac=all, removeamount="all"
)
embedr = nextcord.Embed(
color=nextcord.Color.blurple(),
title="Alle overtredingen van {interaction.user} zijn verwijderd!",
description="Tip: je aan de regels houden werkt echt!",
)
await interaction.response.send_message(embed=embedr)
elif remove == 0:
return ValueError
elif remove == int > 0:
database_functions.infractions(
user_id=user, type="removeW", infrac=all, removeamount=remove
)
Just have a blank character.
help```ansi
[0;31mERROR: Failed building wheel for yarl
Provide more info please.
where exactly?
install*
Could you give the whole traceback?
are u sure?
You cannot use 3.11 yet. If you are please use 3.10
Hey @brittle ocean!
You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.
god
!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.
remove=SlashOption(
required=True,
choices=str(clrinfr),
description='put in "all" or 1-10 or a power of 5',
),
``` this doesn't look valid chief.
as in the str()
Or do you have like an embed somewhere.
ehm yeah
Or does this just need a name.
well i really don't know
Try that.
sure
examples/application_commands/choices.py line 16
choices={"one": 1, "two": 2, "three": 3},```
choices are meant to be name-value pairs
thats weird, it worked with a list of strings too tho
thats a sequence iterable, unlike a string
ah
clrinfr = [ "all",1,2,3,4,5,6,7,8,9,10,15,20,25,30,35,40,45,50,75,100,150, ]
oh god that formatting is horrid
well the idea was that you could choose to remove all infractions or a specific number, so a list of integers and one string
and put that as the choices for the slash option
the attachment is smol
also you could send both embeds in same message lol
Maybe adding it as an image instead of a thumbnail will increase the size? But the dimensions of the actual image file probably also play a part...
Np
is there a way to emulate discord so i can work on a bot offline 
... how does that matter? you can order the first embed first and the second one later
you can send 2 embeds in one message
get raw payloads from somewhere and use them to mock discord events
you can probably use a generator or asyncio events
There must be a good reason for this lol
i know i should ask it in discord api but no one is there so:
how can you detect if a discord websocket connection is closed and the close code?
does python keep a python bible or something?? something that explains the actual workings of the language???
discord doesnt send any special notification to you about it except for exceptions that occur during event exchanges
so its' the job of your library to handle that
the python docs...
how can i do that
i use aiohttp
where exactly do you want to you check if the connection closed, like during connect or after the connection?
both
i tried to find aiohttp docs but i cant find anything about it
ahh okay, I thought it was called python directory instead of docs... thanks!
anyone see the error here?
how do you connect to the gateway in your code
that's an issue with the entrypoint.sh file ( which is probably maintained by the host ), not related to discord.py or python at all
aiohttp.ClientSession().ws_connect
that just connects you to the gateway, won't let you receive / send any events from/ to the API
oh how can i do that
async def listen_gateway(self) -> None:
# _LOGGER.debug("Starting listening to gateway.")
async for message in self.socket:
#if self.is_connected is False:
#self.is_connected = True
#self._client.event_handler.dispatch("GATEWAY_CONNECTED", self._client)
if message.type == aiohttp.WSMsgType.TEXT:
await self._parse_payload_response(json.loads(message.data))
elif message.type == aiohttp.WSMsgType.ERROR:
"error from the gateway!"```
this is what i implemented in my library, `self.socket` there was the Websocket Response returned by `.ws_connect`
ignore the commented out part
i have to change it to this?
that works, but just for once, and yes you should be updating to this to keep listening to events regularly
oh i have a function like this
async def _receiveevent(self):
while True:
event = await self.ws.receive_json()
self.lasts = event['s']
if self.lasts == 11:
_log.debug('received heartbeat ACK')
if self.lasts == 1:
await self._immediate()
if self.lasts == 0:
await self._ready(event)
i use enums for them, makes life easier ```py
async def _parse_payload_response(self, payload: typing.Dict[str, typing.Any]) -> None:
op, t, d = payload["op"], payload["t"], payload["d"]
if op == WSEventEnums.HEARTBEAT_ACK:
self._latency = time.perf_counter() - self.keep_alive.last_heartbeat
return
if op == WSEventEnums.HELLO:
await self._hello_res(d)
elif op == WSEventEnums.DISPATCH:
self.keep_alive.sequence += 1
await self._dispatch_events(payload)
what is WSEventEnums?
it's an enum class that stores the op codes
you shouldn't be using replit for discord bots
Why?
You can develop them but you shouldnt host them
Ok
Ok but can I on my phone with pydroid?
ofcourse
Can you help me make one?
well, ask your problems here 
what;s your experience with python?
I see you have nitro
Avarage begginer
I just know fors ifs whiles
Lists
Import things
- Python data types
- Object Oriented Programming, difference between class and class instances, etc.
- asyncio and async/await syntax
- Loops and iterators
- in, and, or, continue, break, return statements
- Flow control ( if/else/elif , match/case )
this is a short list of things you should be aware about
3 is avoidable when you start, you'll learn about you while you use the library
but 2 is a must.
correct, they are some of them
I never used class @slate swan
U+0031
for two three... 0032 0033?
yup
kk ty
btw how can you detect disconnect?
is there a way to register commands programmatically? like, i have some commands >pat, >hug, >kiss, etc that do very simmilar things, im looking to try and build the commands by looping over a dictionary, and register them that way, is it possible?
sure, though I don't think it's any better than just manually doing those. You basically want to create a coroutine without the command decorator, and instantiate a Command class with all the args you would usually pass to the command decorator, and you use the coroutine as your callback. Then you just add_command
async def callback(ctx: commands.Context, ...) -> Any:
...
command = Command(callback, name="...", aliases=["...", "..."], ...)
bot.add_command(command)
another alternative is to make a "parent" command and use aliases in conjunction with Context.invoked_with, but that might not look very good if you've got a help command
ooh, yeah, yeah, good idea. it will be a bit better because i have like 30 of these reaction commands
and itll make it easier to add new ones
they basically all call one function, so i can just use partials to generate it from strings in a dictionary
its like this py @commands.command(name='pat') async def pat(ctx, target, *extra): await do_reaction(ctx, target=target, folder="pat", message="&u pat &t") so i can just use a dict as args for do_reaction
I stopped coding for 1 year and a half and might need to read the whole python documents again 🙄 you guys already know the out put of this, it sends a message then edits it, sends another message then edits it since im running message.edit and ofc thats what its supposed to do, but what im trying to so is keep editing the same message
async def test(ctx):
count = 0
while True:
#print(count)
message = await ctx.send(count)
count += 1
await asyncio.sleep(1)
await message.edit(content=count)```
Move the message = await ctx.send(count) out of the while loop
Though it seems like this is just a countdown type timer?
I think it might be better to use something like <t:1669340096:R>
Its a command to test a rate limit on diff channels of a server because im trying to make a command where a message needs to be updated 5 times every 5 seconds until the game ends
But its gonna be a struggle cause what if 3 ppl do the command in diff channels of the server or some
That's the rate limit
5 message edits/sends per 5 seconds
Ye but is that per message? Or it can be editing like 7 diff messages 5 times/5seconds?
Its global
Oof
Trying to do something that updates frequently in discord is not a good idea
Shit so hard
Yep, my idea got ruined
Can never code my ideas
I am trying to get him to choose a name from a list and place it as in the photo but it comes out as what is in the second photo
fasoto = open("namesrandom.txt", "r")
archivononame = open('nameselecti.json','w')
archivononame.write("")
archivononame.close()
pediatra = fasoto.readlines()
pediatrato = f'{random.choice(pediatra)}"'
username = '"username"'
aline = f'"{pediatrato}'
with open("nameselecti.json", "a") as pediatro:
pediatro.write('{' + "\n" + f" {username}:{aline}" + '}')
After every dropdown call add one thing
self.stop()
\1️⃣
Just put this
For default emojis bot doesn't need unicodes to use
But for custom emoji they need this sequence: <:name:id>
like
!python
This thing is for this custom emoji: 
damn i didn't know that
Discord stoopid why couldn't they do like <e:123456789012345678> syntax, the heck for is separating animated emojis and even using their names
Also do they still not let you copy emoji ID like a normal ID
well on browser u can open image in new tab with emoji kek
get the id from there
On desktop you can copy link but that's not what I call normal way
Normal way would be "copy ID" button
¯_(ツ)_/¯
I am gonna complain to their support about this
best just make emoji global 
💪🤗💪
🦵 🦵
Just put\<emoji> to get he id ez as that
Ooo, thanks. Learnt something new
Sometimes it doesn't work for some reason
Button better
dosent work for animated
!pepo_lol
Emoji: 
u have nitro thats why
Oh, forgot. my bad :[
@bot.event
async def on_message(message):
embeds = message.embeds
for embed in embeds:
print(embed.to_dict())
So I have this code, but for testing purposes I want to make it so I can just pick a specific embed to turn into the dict. How do I do that?
what are snowflake ids?
Using index
more info plz
!e
embeds = ["blah", "buh", "beh"]
print(embeds[1])
@naive briar :white_check_mark: Your 3.11 eval job has completed with return code 0.
buh
🤷
How do I get the past embed though?
Yes
Be more specific.
Ahh like a seconds
Like today is nov 25, 2022 = so many seconds
<t:126377373:R>
i mean what is Internal worker ID and Internal process ID
Unfortunately I don't have much information about snowflake id's tho :[[
i wanna know how can you get the ids you receive in a gateway event
O.o
@miner.tree.command(name='unbanid', description='unbans an id from a server, bot must be in it')
@app_commands.describe(user = 'Put a userid!')
async def unbanid(a: discord.Interaction, user: str):
username = a.guild.get_member(user)
await a.guild.unban(username)
await a.response.send_message(f"Unbanned {username}")
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/runner/crypto-miner-bot/venv/lib/python3.8/site-packages/discord/app_commands/tree.py", line 1242, in _call
await command._invoke_with_namespace(interaction, namespace)
File "/home/runner/crypto-miner-bot/venv/lib/python3.8/site-packages/discord/app_commands/commands.py", line 887, in _invoke_with_namespace
return await self._do_call(interaction, transformed_values)
File "/home/runner/crypto-miner-bot/venv/lib/python3.8/site-packages/discord/app_commands/commands.py", line 880, in _do_call
raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'unbanid' raised an exception
Full traceback please.
Traceback (most recent call last):
File "/home/runner/crypto-miner-bot/venv/lib/python3.8/site-packages/discord/app_commands/commands.py", line 862, in _do_call
return await self._callback(interaction, **params) # type: ignore
File "main.py", line 51, in unbanid
await a.guild.unban(username)
File "/home/runner/crypto-miner-bot/venv/lib/python3.8/site-packages/discord/guild.py", line 3481, in unban
await self._state.http.unban(user.id, self.id, reason=reason)
AttributeError: 'NoneType' object has no attribute 'id'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/runner/crypto-miner-bot/venv/lib/python3.8/site-packages/discord/app_commands/tree.py", line 1242, in _call
await command._invoke_with_namespace(interaction, namespace)
File "/home/runner/crypto-miner-bot/venv/lib/python3.8/site-packages/discord/app_commands/commands.py", line 887, in _invoke_with_namespace
return await self._do_call(interaction, transformed_values)
File "/home/runner/crypto-miner-bot/venv/lib/python3.8/site-packages/discord/app_commands/commands.py", line 880, in _do_call
raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'unbanid' raised an exception: AttributeError: 'NoneType' object has no attribute 'id'
yeah username is none
you'd be better off typing user to be a discord.User and handle UserNotFound in an error handler
that doesnt exist and its not better than what he's currently doing
sorry bot.get_user 💀
wait using get_member wont even work in the first place 💀
how do you unban someone whos in the server?
But member too exist as far i know
He is trying to unban a member with the member id
So ofc the member will be not in the server
well he cant unban a member, he can only unban users
Ye make sense
Need to use bot.get_user method
can I get a member in the bans?
tldr just typehint user to be a discord.User/use UserConverter
Also changed that user: str to user: int
Need to use ban entry
well or you can take an int and try to guild.fetch_ban
try-except it, if it fails then theyre not banned, if no errors are raised then theyre banned
Well imma show quick example:
@miner.tree.command(name='unbanid', description='unbans an id from a server, bot must be in it')
@app_commands.describe(user = 'Put a userid!')
async def unbanid(a: discord.Interaction, user: int):
username = bot.get_user(user)
await a.guild.unban(username)
await a.response.send_message(f"Unbanned {username}")
Here i just edited your code
not it doesn't, that should be py-cord
Nextcord too uses it
you don't need to get the user, you can simply pass a discord.Object
no it doesn't
I am showing the interaction.send and interaction.edit method
!d nextcord.Interaction.send
Here @upbeat otter
That guy wishes if he could use ctx
So i just showed example 💀
I don't even remember the convo so anyways
;-;
He was trying to unban with user id ;-;
Traceback (most recent call last):
File "F:\fun\Desktop\coding practice\python practice\test.py", line 7, in <module>
client.run()
File "F:\fun\Desktop\coding practice\python practice\x\client.py", line 17, in run
asyncio.run(self._http.run())
^^^^^^^^^^^^^^^^
File "F:\fun\Desktop\coding practice\python practice\x\httpc.py", line 33, in run
asyncio.run(self.init())
File "C:\Program Files\Python311\Lib\asyncio\runners.py", line 190, in run
return runner.run(main)
^^^^^^^^^^^^^^^^
File "C:\Program Files\Python311\Lib\asyncio\runners.py", line 118, in run
return self._loop.run_until_complete(task)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Program Files\Python311\Lib\asyncio\base_events.py", line 650, in run_until_complete
return future.result()
^^^^^^^^^^^^^^^
File "F:\fun\Desktop\coding practice\python practice\x\httpc.py", line 41, in init
await self._connect()
File "F:\fun\Desktop\coding practice\python practice\x\httpc.py", line 45, in _connect
async with self.cs.ws_connect(self.url) as ws:
File "C:\Users\fun\AppData\Roaming\Python\Python311\site-packages\aiohttp\client.py", line 1141, in __aenter__
self._resp = await self._coro
^^^^^^^^^^^^^^^^
File "C:\Users\fun\AppData\Roaming\Python\Python311\site-packages\aiohttp\client.py", line 779, in _ws_connect
resp = await self.request(
^^^^^^^^^^^^^^^^^^^
File "C:\Users\fun\AppData\Roaming\Python\Python311\site-packages\aiohttp\client.py", line 400, in _request
raise RuntimeError("Session is closed")
RuntimeError: Session is closed``` httpc.py:https://paste.pythondiscord.com/aporoqanej client.py:https://paste.pythondiscord.com/uhogoloped
Show code.
i shown
Ohk
The session is closed after this with statement block is finished
how can i write discord mirror channel bot? Firstly i need to connect to websocket right?
and have open browser with already logged in account and have opened channel which i want to mirror right?
You can simply use session.get without using the session as a context manager, but you could get a warning about unclosed session after the program ends. Like:
async with self.cs.get(...) as resp:
...
Another way that you can ensure that the session will be closed after the program ends is to make a start or main function where you can make the session a context manager and just pass the session in the class constructor. Like:
async def main():
async with aiohttp.ClientSession as cs:
client = Client(session=cs, ...)
ok ty
ive got another problem
now nothing happened and it didnt seems like successfully connected to websocket
nvm its working
nextcord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In options.1.choices.0.value: Could not interpret "1" as string.
In options.1.choices.1.value: Could not interpret "2" as string.
In options.1.choices.2.value: Could not interpret "3" as string.
In options.1.choices.3.value: Could not interpret "4" as string.
In options.1.choices.4.value: Could not interpret "5" as string.
How is this happening?
@bot.slash_command(guild_ids=GUILD_IDS)
async def clearinfracs(
interaction: Interaction,
user: nextcord.Member = SlashOption(
required=True,
description="The user to remove the infractions from",
),
remove=SlashOption(
choices=[1, 2, 3, 4, 5],
required=True,
description="put in 00 to remove all or 1-10 or a power of 5",
),
):
await guild.unban(discord.Object(id = user_id))
will do it
All choices must be a string
Oooo sheesh
I didn't know about that
Thanks ;-;
really?
Ofc
didn't know that
explain this then
(parameter) choices: Dict[str, str | int | float] | Iterable[str | int | float] | None
choices can def be an int lol
yeah i though as much, why else would it give that option
but why is it giving the error then?
Yo lol
try setting a dictionary instead, like so -
{
"one": 1,
"two": 2
}
no clue here is an example tho
@bot.slash_command(guild_ids=[TESTING_GUILD_ID])
async def choose_a_number(
interaction: nextcord.Interaction,
number: int = SlashOption(
name="picker",
choices={"one": 1, "two": 2, "three": 3},
),
):
"""Repeats your number that you choose from a list
Parameters
----------
interaction: Interaction
The interaction object
number: int
The chosen number.
"""
await interaction.response.send_message(f"You chose {number}!")
how does on mention work
sounds like someone will have to read the docs
bruh he can use a searchbar himself
and search on_mention
what r u tryna to do?
i want bot to send a messsage when pinged by a specific user
U can use on_message too
Yep that works
pass this as commd_prefix
It's for the prefix only tho 💀
If you want the bot to show a message when mentioned you need to use event
can someone give me a quick example
@slate swan i am using on message
Wait please
how to let my bot send message to channel with specific id
channel=bot.get_channel(channel_ID)
await channel.send("Hello!")
@bot.event
async def on_message(message):
if bot.user.mention in message.content:
await message.channel.send("your message")
await bot.process_commands(message)
AttributeError: 'NoneType' object has no attribute 'send'

da
Check you're passing the correct ID and don't do it in on_ready
thanks for replying that for me :))
sometimes its just caching issues lol
Oh yeah, question of my own...
Forgot to mention, bot should be in that guild from where the channel is
When I do something along the lines of:
channel = self.bot.get_channel(941380693164949574)
print(channel)
It prints only the channel name and nothing else. Is this normal? Just curious.
🤷
it should not print channel name tho 💀
it should print channel objects
Exactly
like name, id
try printing channel.id
Yup just did and it works as expected
!eval
channel = bot.get_channel(343944376055103488)
print(channel)
oh forgot 💀
I can even send stuff into that channel
then maybe discord library issues lol
that is normal, channel objects implement a __str__ method that returns the name of the channel, and print() will prefer it over the more verbose __repr__
when the code exits that async with context handler you were disconnected
or the api will send an error warning too
oh i already got it thanks for the help
anyone got good tutorial video for discord bot? (updated if possible)
swastik
or glowstik
search them in yt
does he have the updated version with button?
yes
alright and you only need python bases right?
ye
alr ty
;]
show code
import discord
from discord.ext import commands
client = commands.Bot(command_prefix = "d!")
@client.event
async def on_ready():
print("Bot is ready")
client.run("")```
I get this error
!intents
Using intents in discord.py
Intents are a feature of Discord that tells the gateway exactly which events to send your bot. Various features of discord.py rely on having particular intents enabled, further detailed in its documentation. Since discord.py v2.0.0, it has become mandatory for developers to explicitly define the values of these intents in their code.
There are standard and privileged intents. To use privileged intents like Presences, Server Members, and Message Content, you have to first enable them in the Discord Developer Portal. In there, go to the Bot page of your application, scroll down to the Privileged Gateway Intents section, and enable the privileged intents that you need. Standard intents can be used without any changes in the developer portal.
Afterwards in your code, you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:
from discord import Intents
from discord.ext import commands
# Enable all standard intents and message content
# (prefix commands generally require message content)
intents = Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix="!", intents=intents)
For more info about using intents, see discord.py's related guide, and for general information about them, see the Discord developer documentation on intents.
is that new update or something
Maybe maybe maybe
then define intents
yes
What?
what am I supposed to do then
If you read all of it
You'll clearly see that it is literally telling you how
import discord
intents=discord.Intents.all()
bot = commands.Bot(......, intetns=intents)
#for this method you have to enable all intents in your app!
But with this u don't need to turn on all intents
commands.bot(command_prefix="!", intents=Intents.default()
whatever u need
I didn't say you need to? 😕
also
i would like to mention
you have to add extra line
from discord import Intents
Wait
I was telling that guy ahhh
I'm an idiot
@slate swan do you have updated tutorial because the channel you said me to watch are outdated
It was updated gimme a quick sec
Oh Civo
I forgot about that guy
He has updated things
!d intents
embed.set_image(url=".....")
oh great thanks but i am wondering rn how can i send custom string to this channel
i mean that i want to pass an argument somehow
i mean like that
but i cant do it in that way
like some strings i guess
anyone know how to add slash commands?
Forgot uf
and images
Yes
how
Oh
im just writing script and im on the last step
Wait 1 min
ok
and need just to send this what i received from earlier function
but i dont know how i can pass it
Ahhhhh

!d discord.ext.commands.Context.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.
This works similarly to [`send()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Messageable.send "discord.abc.Messageable.send") for non-interaction contexts.
For interaction based contexts this does one of the following...
Thanks bruh
i hate this discord things... xd
teach me slash commamds
application commands
Gimme some secs
If you are using discord.py. Here is an example:
@bot.tree.command(name="slash-command-name", description="Command description")
async def slash(interaction: discord.Interaction):
await interaction.response.send_message("Hello! You used a slash command.")
Here take 💀
What importa do
Useful things 🌚
i have no idea how to use it 😭
i mean i cant use await i think
because its not in async function
idk
yep
discord.py couldn't find the channel
is the bot already in the guild ?
Does the bot have access to that channel?
Also it looks like you're using asyncio.run() to call it - so it's not out of the question that the bot's cache isn't populated just yet
it has access it has sent message like 2 minutes ago with different written function
intents = discord.Intents(messages=True, guilds=True, message_content = True)
client = discord.Client(intents=intents, case_insensitive=True)
async def szef(param):
channel = client.get_channel(1014245637245653125)
await channel.send(param)
asyncio.run(szef('Hello im SSR'))
The bot isn't even on
ugm sorry i have it written like that
intents = discord.Intents(messages=True, guilds=True, message_content = True)
client = discord.Client(intents=intents, case_insensitive=True)
async def szef(param):
channel = client.get_channel(1014245637245653125)
await channel.send(param)
asyncio.run(szef('Hello im SSR'))
client.run('t0ken')
Almost
ok i change it
to this
intents = discord.Intents(messages=True, guilds=True, message_content = True)
client = discord.Client(intents=intents, case_insensitive=True)
client.run('t0ken')
async def szef(param):
channel = client.get_channel(1014245637245653125)
await channel.send(param)
asyncio.run(szef('Hello im SSR'))
it looks like it works but bot doesnt send message
Try the same code but with commands
Why u using async?
I think it should be
def szef(param):
Yep
RuntimeWarning: coroutine 'szef' was never awaited
szef('Hello im SSR')
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
Do
await asyncio.run()
import asyncio
from discord import Client, Intents
intents = Intents.default()
client = Client(intents=Intents)
@client.event
async def on_ready() -> None:
# Example code, do not use in practise
channel = client.get_channel(1014245637245653125)
await channel.send("cheese")
async def main() -> None:
async with client:
await client.start("token")
if __name__ == "__main__":
asyncio.run(main())
Run is not awaited.
Is it possible to stop links from embedding with either web-hook or normal message?
Can't find anything on the docs
<url>
thanks
hey @slate swan, you around?
this is the best solution
Eating rn ;-;
wtf bro
thanks it worked ❤️
alright, enjoy your food. Tag me when your done.
Kk
i was struggling with this for a bit thanks brother @cloud dawn
Magic fingers 🐒 😏
indeed haha
But if you want to send a message only on launch you should approach it differently.
oh shit but how i can set custom string now to be send?
Just change cheese.
Or do you want to change it trough a command?
no i dont want to do that in that way
i need to pass argument from earlier function
like previous one
I think they mean currently that on_ready() can't take custom arguments that need to be passed into the channel.send()
Okay a bit more difficult but I'll get it as close as possible.
Wait for it...
Right because we can't do it in setup_hook (cache is not populated)
exactly
@high tapir you could do:
class CustomBot(commands.Bot):
def __init__(self, *args, **kwargs) -> None:
super().__init__(*args, **kwargs)
async def setup_hook(self) -> None:
channel = await self.fetch_channel(123456789)
await channel.send("Some message")
bot = CustomBot(command_prefix="!", intents=discord.Intents.default())
bot.run()
But that goes back to the issue of custom text
hello
yup i need custom text
import asyncio
from discord import Client, Intents
intents = Intents.default()
class AmazingClient(Client):
def __init__(self, msg: str) -> None:
self.msg = msg
super().__init__(intents=intents)
async def on_ready(self) -> None:
# Example code, do not use in practise
channel = client.get_channel(1014245637245653125)
await channel.send(self.msg)
async def main(msg: str) -> None:
async with client:
await AmazingClient(msg).start("token")
if __name__ == "__main__":
asyncio.run(main("cheese"))
and i call it with AmazingClient('hello') e.g ?
or here i pass the argument
i mean where i can put my string that i want to print
You can't send messages in the setup hook since it's before the websocket connection.
yeah basically
Sending messages doesn't require a websocket connection though does it
You've peaked my interests.
andfiltering messaged
from channel and i want to send some of this messages
and this is my "custom string" that i want to send
the token is not verified yet tho, static login has not been performed
might work mb
He does fetch it so..
I would probably extract it into a seperate function: @high tapir
async def send_message(message: str, *, channel: discord.Channel) -> discord.Message:
return await channel.send(message)
class CustomBot(commands.Bot):
async def setup_hook(self) -> None:
channel = await self.getch_channel(123456) # this will fetch from API
await send_message("This is set on setup_hook!", channel=channel)
async def getch_channel(self, channel_id: int) -> Optional[discord.Channel]:
if channel := self.get_channel(channel_id):
return channel
else:
return await self.fetch_channel(channel_id)
bot = CustomBot(...)
@bot.command()
async def some_command(ctx: commands.Context, ...) -> None:
channel = await self.getch_channel(123456) # this will get from cache
await send_message("This was sent in a command, later on", channel=channel)
This way you have an extracted function you can call whenever
Just a proof of concept I came up on the spot, lol. Not guaranteed to work
I've sent messages using my bot with just the REST API without a websocket connection. It should work just fine
if the discord.py rest client was designed well, it would allow you to do this without any dependence on the websocket
the rest isnt attached to the client until the start gets called
i think the rest is, but the session is not, either one of these
Worth a shot. In my head, if I can send a message via rest api without a socket connection, discord.py should be able to let you as well. But I haven't tested it with discord.py so not sure
Well the setup_hook gets called after start/run has been called, yes?
async def login(self, token: str) -> None:
_log.info('logging in using static token')
if self.loop is _loop:
await self._async_setup_hook()
if not isinstance(token, str):
raise TypeError(f'expected token to be a str, received {token.__class__.__name__} instead')
token = token.strip()
data = await self.http.static_login(token)
self._connection.user = ClientUser(state=self._connection, data=data)
self._application = await self.application_info()
if self._connection.application_id is None:
self._connection.application_id = self._application.id
if not self._connection.application_flags:
self._connection.application_flags = self._application.flags
await self.setup_hook()
Setup hook is the last thing in the login so it will most likely work.
dont know whats going on here there 👍
Ah yeah rest client is attached before setup hook
we should be ok then
that should work then
Looks like Danny had the foresight to design it that way
You made a discussion possible where I once again dived in the source.
@coral mirage now tell
Hello I have a question. On my chromebook intents.message_contents = True works but on my windows pc I get the error: AttributeError: 'Intents' object has no attribute 'message_content'
Can someone help me with this?
Did u upgrade your library?
Update discord.py
ohw
Your chromebook is on v2.0 while your windows PC is not, update your windows PC to 2.0
hm you can just ```py
client = Client(...)
client.event(lambda setup_hook *_: client.http.send_message("your text"))
Same answer on same time cool
oh i missed it this is for custom strings to be send right?
So, I want to invoke a command inside another command. Idk if you familiar with select and buttons, but I'm trying to select a command. I try what you told me and I actually have an idea, but I'm still missing something.
idk if its invoke
You can't really invoke a command but just copy paste the code of that command and put it on dropdown call back
The best way to do this would be to extract logic of the command into a seperate function
Idk better idea, but i use this
Cogs?
can you send an example?
Why not access the attr directly over using Client.event?
can you send me a example?
async def some_command(ctx: commands.Context, ...) -> None:
# logic goes here
@bot.command(name="some_command")
async def _some_command(ctx: commands.Context, ...) -> None:
await some_command(ctx, ...)
class MyView(discord.ui.View):
...
@discord.ui.button(...)
async def callback(self, ...) -> None:
await some_command()
Oh u were telling me ;-;
Nvm he gave
do you guys get pay to help out?
Yes
how you planning to run the client then
Cool
wtf it looks complicated what do i need to replace? to start setting my strings i dont understand this part this also
huh
sorry i misread it
😃
discord.TextChannel
TypeError: Callback is already a command.
yeah thats possible as well, but that's what client.event will do internally anyways
umm
from typing import Optional
what does that error mean?
Yeah, hence my question🦦
im' lazy to type =
Can relate
can you visit my server ?
Dm
and how do i call to set my custom string? sorry but im not familiar with this discord py web and i hate this shit i just need to print one thing.....
async def send_message(message: str, *, channel: discord.Channel) -> discord.Message:
return await channel.send(message)
class CustomBot(commands.Bot):
async def setup_hook(self) -> None:
channel = await self.getch_channel(1014245637245653125) # this will fetch from API
await send_message("This is set on setup_hook!", channel=channel)
async def getch_channel(self, channel_id: int) -> Optional[discord.Channel]:
if channel := self.get_channel(channel_id):
return channel
else:
return await self.fetch_channel(channel_id)
bot = CustomBot(...)
@bot.command()
async def some_command(ctx: commands.Context) -> None:
channel = await self.getch_channel(1014245637245653125) # this will get from cache
await send_message("This was sent in a command, later on", channel=channel)
?
It means the function object has already been registered as a command
okay in custombot(mytoken) right?
Just call send_message("YOUR TEXT HERE", channel=CHANNEL_HERE)
note that channel needs to be a discord.Channel object and not a primitive datatype like a string for a channel name or an integer ID
so like there are 2 commands with the same name?
why is getch_channel so long? just do
async def getch_channel(self, channel_id: int) -> Optional[discord.Channel]:
return self.get_channel(channel_id) or await self.fetch_channel(channel_id)
how can i get this discord.Channel object?
No, can you show your whole traceback and code?
from getch_channel
yeah i think this shit is too hard for me i dont understand this weird library at all i stopped on that, thanks for your help rob anyways
async def send_message(message: str, *, channel: discord.Channel) -> discord.Message:
return await channel.send(message)
class CustomBot(commands.Bot):
async def setup_hook(self) -> None:
channel = await self.getch_channel(1014245637245653125) # this will fetch from API
await send_message("This is set on setup_hook!", channel=channel)
async def getch_channel(self, channel_id: int) -> Optional[discord.Channel]:
if channel := self.get_channel(channel_id):
return channel
else:
return await self.fetch_channel(channel_id)
bot = CustomBot('t0ken')
@bot.command()
async def some_command(ctx: commands.Context) -> None:
channel = await self.getch_channel(1014245637245653125) # this will get from cache
await send_message("This was sent in a command, later on", channel=channel)
send_message("YOUR TEXT HERE", channel=)
there was an empty bot.command
but have the feeling that im missing just one thing untill success xd
what does not work
async def send_message(message: str, *, channel: discord.Channel) -> discord.Message:
AttributeError: module 'discord' has no attribute 'Channel'. Did you mean: 'channel'?
@bot.command
async def balance(ctx):
user_id = ctx.author.id
if find_member(user_id) == None:
insert_user(ctx.author.id)
user_info = find_member(ctx.author.id)
embed=discord.Embed(title=f"{ctx.author.display_name}'s balance", description=f"You have {user_info['coins']}", color=0xFF5733)
embed.set_author(name=ctx.author.display_name,icon_url=ctx.author.avatar_url)
await ctx.send(embed=embed)```
discord.TextChannel might work
when I type $balance it says no command foound
@bot.command**()**
and you should use is in if find_member(user_id) == None:
Oh yeah sorry. Replace all discord.Channel with discord.TextChannel
I am really dumb
Too early for this shit sorry
what is is?
!d is
async def send_message(message: str, *, channel: discord.TextChannel) -> discord.Message:
return await channel.send(message)
class CustomBot(commands.Bot):
async def setup_hook(self) -> None:
channel = await self.getch_channel(1014245637245653125)
await send_message("This is set on setup_hook!", channel=channel)
async def getch_channel(self, channel_id: int) -> Optional[discord.TextChannel]:
if channel := self.get_channel(channel_id):
return channel
else:
return await self.fetch_channel(channel_id)
bot = CustomBot('t0ken', intents=intents)
@bot.command()
async def some_command(ctx: commands.Context) -> None:
channel = await self.getch_channel(1014245637245653125)
await send_message("This was sent in a command, later on", channel=channel)
send_message("YOUR TEXT HERE", channel=discord.TextChannel)
send_message("YOUR TEXT HERE", channel=discord.TextChannel)
RuntimeWarning: Enable tracemalloc to get the object allocation traceback Last error i guess
Get rid of the last line
Make sure you actually define intents too
Internally the process of both operators is different, and leading to such a bad practice may "bite" you in the future
intents = discord.Intents.default()
intents.message_content = True
bot = CustomBot("token", intents=intents)
!e
print(0 == False, 0 is False)
@primal token :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | <string>:1: SyntaxWarning: "is" with a literal. Did you mean "=="?
002 | True False
yeah but if i remove it i wont be able to set custom string wont i?
How would I make it so even after the bot restarts it saves the value of seomthing?
For example by default when I do "-welcome" it says Welcome to the server #user, but when I do -welcome (Welcome Message) it says the message I chose, and continues to after it restarts
@primal token @sick birch hel please
oh k
So you have a list of welcome messages you can choose from?
No, they choose the message
Like write it themselves
per guild i suppose?
You can use JSON or if you're going to other guilds to avoid further trouble you can use sqlite with an async driver
hey im currently working on an scraper bot, which scrapes site information with requests. Im using a discord bot for the commands so when i f.E am typing ' !scrape build' its replacing the {query} i defined in the link so its inserting the 'build' into the link. But im currently stuck and arent getting a response from the bot.
@client.event
async def on_message(message):
if (message.channel.id == 1003326813558280293):
author = message.author
image_url = message.attachments[0].url``` how to fix this error ?
it means the message didnt have attachments and no need for the brackets in the condition
anyways will anyone know how to shut down log bot in then shut down ?
def szef_test(a):
intents = discord.Intents.default()
intents.message_content = True
client = discord.Client(intents=intents, case_insensitive=True)
@client.event
async def on_ready():
channel = client.get_channel(1014269272467456130)
await channel.send(a)
client.run('t0ken')
client.close()
return
RuntimeWarning: coroutine 'Client.close' was never awaited
client.close()
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
but if it is an image, there is necessarily the url of the image
anyone idea how i can do it then?
That's correct, do you have the message_content intent on?
yes
all intents are activated
Can you show your code and if the code is correct then you would need to check if the message has an attachment in the first place
import requests
import discord
from discord.ext import commands
intents = discord.Intents.default()
intents.members = True
client = commands.Bot(command_prefix='!', intents=intents)
@client.event
async def on_message(message):
if (message.channel.id == 1003326813558280293):
author = message.author
image_url = message.attachments[0].url
req = requests.get(image_url, stream=True)
if req.status_code == 200:
embed = discord.Embed(
title=f'Nouveau Succès de {author}',
colour=discord.Colour.blue()
)
await message.channel.send(embed=embed)
client.run('token')```
@primal token
you're missing the message_content intent!
add intents.message_content = True under intents.members = True
ok thanks, I'll try
it works!
🦦
why aiohttp ? it's better than requests
Why do we need asynchronous programming?
Imagine that you're coding a Discord bot and every time somebody uses a command, you need to get some information from a database. But there's a catch: the database servers are acting up today and take a whole 10 seconds to respond. If you do not use asynchronous methods, your whole bot will stop running until it gets a response from the database. How do you fix this? Asynchronous programming.
What is asynchronous programming?
An asynchronous program utilises the async and await keywords. An asynchronous program pauses what it's doing and does something else whilst it waits for some third-party service to complete whatever it's supposed to do. Any code within an async context manager or function marked with the await keyword indicates to Python, that whilst this operation is being completed, it can do something else. For example:
import discord
# Bunch of bot code
async def ping(ctx):
await ctx.send("Pong!")
What does the term "blocking" mean?
A blocking operation is wherever you do something without awaiting it. This tells Python that this step must be completed before it can do anything else. Common examples of blocking operations, as simple as they may seem, include: outputting text, adding two numbers and appending an item onto a list. Most common Python libraries have an asynchronous version available to use in asynchronous contexts.
async libraries
The standard async library - asyncio
Asynchronous web requests - aiohttp
Talking to PostgreSQL asynchronously - asyncpg
MongoDB interactions asynchronously - motor
Check out this list for even more!
What
image of a url hmm
not sure if its literally the question or said opposite since it seems valid either way
*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
(couldn't post media in general, so posting here)
when I click on that profile I was for a moment get scared and think that a "something" is related hidden part underneath discord 
Basically this popup didn't fit in height, so instead of relocating above it shift whole discord layout adding space underneath (dark area). The whole discord stays "lifted" in this state until I click view server.
can someone tell me what I'm missing please 😦
Interaction always comes before the item
return await self._callback(interaction, **params) # type: ignore
File "/home/container/main", line 137, in crash
if interaction.author.id != bot.user.id:
AttributeError: 'Interaction' object has no attribute 'author'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/container/.local/lib/python3.10/site-packages/discord/app_commands/tree.py", line 1242, in _call
await command._invoke_with_namespace(interaction, namespace)
File "/home/container/.local/lib/python3.10/site-packages/discord/app_commands/commands.py", line 887, in _invoke_with_namespace
return await self._do_call(interaction, transformed_values)
File "/home/container/.local/lib/python3.10/site-packages/discord/app_commands/commands.py", line 880, in _do_call
raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'crash' raised an exception: AttributeError: 'Interaction' object has no attribute 'author'
So, swap the select and interaction position in the callback argument
!d discord.Interaction.user
The user or member that sent the interaction.
File "/home/container/main", line 138, in crash
await interaction.response.send_message(embed=discord.Embed(description=f"Check your direct messages! {message.author.mention}",
NameError: name 'message' is not defined
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/container/.local/lib/python3.10/site-packages/discord/app_commands/tree.py", line 1242, in _call
await command._invoke_with_namespace(interaction, namespace)
File "/home/container/.local/lib/python3.10/site-packages/discord/app_commands/commands.py", line 887, in _invoke_with_namespace
return await self._do_call(interaction, transformed_values)
File "/home/container/.local/lib/python3.10/site-packages/discord/app_commands/commands.py", line 880, in _do_call
raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'crash' raised an exception: NameError: name 'message' is not defined
lmafo
plssssssssss
Thank You!!!! Finally Work!
is it possible to only view certain buttons at a specific embeds
can someone advise me free hosting for bot?
There isnt really any good free hosting services for such applications, if you're looking for a VPS you may look in #965291480992321536
What's the problem
Turn on message_content intent
!d discord.Intents.message_content
Whether message content, attachments, embeds and components will be available in messages which do not meet the following criteria:
• The message was sent by the client
• The message was sent in direct messages
• The message mentions the client
This applies to the following events...
Using intents in discord.py
Intents are a feature of Discord that tells the gateway exactly which events to send your bot. Various features of discord.py rely on having particular intents enabled, further detailed in its documentation. Since discord.py v2.0.0, it has become mandatory for developers to explicitly define the values of these intents in their code.
There are standard and privileged intents. To use privileged intents like Presences, Server Members, and Message Content, you have to first enable them in the Discord Developer Portal. In there, go to the Bot page of your application, scroll down to the Privileged Gateway Intents section, and enable the privileged intents that you need. Standard intents can be used without any changes in the developer portal.
Afterwards in your code, you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:
from discord import Intents
from discord.ext import commands
# Enable all standard intents and message content
# (prefix commands generally require message content)
intents = Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix="!", intents=intents)
For more info about using intents, see discord.py's related guide, and for general information about them, see the Discord developer documentation on intents.
What channel?
Probably #965291480992321536
Can somone help me
@sick birch I've made that oauth2 request work
What's the ratelimit for that?
like adding members back to guild
those last two lines are (extremely) outdated code, dpy's renamed all server attributes to guild and changed Client.add_roles() to Member.add_roles()
!d discord.Member.add_roles < most up to date version of the documentation @slate swan
await add_roles(*roles, reason=None, atomic=True)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Gives the member a number of [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role "discord.Role")s.
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 added [`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.
Python documentation is for python
Discord.py documentation is for discord.py a library of python
Why would Pythons docs feature discordpy's docs?
On the even on_member_ban How can i check how many members has been banned
!d discord.Guild.bans
async for ... in bans(*, limit=1000, before=..., after=...)```
Retrieves an [asynchronous iterator](https://docs.python.org/3/glossary.html#term-asynchronous-iterator "(in Python v3.11)") of the users that are banned from the guild as a [`BanEntry`](https://discordpy.readthedocs.io/en/latest/api.html#discord.BanEntry "discord.BanEntry").
You must have [`ban_members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.ban_members "discord.Permissions.ban_members") to get this information.
Changed in version 2.0: Due to a breaking change in Discord’s API, this now returns a paginated iterator instead of a list.
Examples
Usage...
It gets invoked for each user
Oh
Fuck so in case of a massban ratelimit would be crazy
I will unban just the people that allowed the OAuth2 hopefully avoiding the ratelimit
an example usage: ```py
Get a role object (typically by role ID)
role = ctx.guild.get_role(1234)
Add it to the command author
await ctx.author.add_roles(role)```
If you can 100% confirm that the role will never not be there, you could safely skip the cache all together and use discord.Object(id=...)
Big brain time
ID as in the numeric identifier given to the role
if you have the developer mode enabled in your discord app, you can right click the role and copy the ID there
you didnt define the member variable in your function...
didn't see ctx.reply in a while 🥹
the first parameter of that command, ctx, is the commands.Context object, and it contains a lot of helpful attributes for you to do things from your command
/ commands are just better
for example, ctx.author gives you the user/member that invoked your command
how do i send emojis in custom or custom animated emojis disnake again?
The function is already a callback of an command
Send the code of the function
With its decorators
Or just the decorators
Sorry bit busy with the help system migration atm
?
Everyone is a volunteer here, so you are not entitled to get help at all times. Ask your question, and if someone can help they will.
is there a way to turn the user flags(integer) back to 1 << something value?
or is there a way to calculate it?
the moderation role it pingable to report people not following to rules, not to ask for hlep
Am i doing something wrong in this code?
Because it won't unban the user that has been banned on_member_ban and ofc it won't rejoin the guild
you can check if a flag exists in the final value value & flag iirc
that way you can get the flags that exist in the value
discord/flags.py lines 171 to 172
def _has_flag(self, o: int) -> bool:
return (self.value & o) == o```
this is how dpy handles it
there's already a command called pof, you can't have 2 of them
@bot.command(commands) ????
those parts of code wont get executed if oauth_response is None ( or any other Falsy value) , can you try printing it
Docker is weird. Prints won't be executed
what?
@commands.Cog.listener()
async def on_member_ban(self, guild, user):
async for i in guild.audit_logs(
limit=1,
after=datetime.datetime.now() - datetime.timedelta(minutes=1),
action=disnake.AuditLogAction.ban,
):
print("before resp")
oauth_response = await OAuth2User.get_or_none(discord_id=user.id)
print("after")
if oauth_response:
print("unban")
await guild.unban(
user, reason=f"{user.name} Has been added back via OAuth2"
)
logger.info(f"Unbanned {user}-{user.id} from {guild.name}-{guild.id}")
logger.info(f"Re-adding member {user.id} to {guild.id}.")
print("adding")
await add_to_guild(oauth_response.token, user.id, guild.id)
raise Exception("a")
@slate swan does this look wrong to u?
prints and exceptions won't raise for some weird reasons.. docker its just fucked up
print(...)
hey. i haven't made a discord bot since the original library stopped maintenance. where's the current one that everyone is using?
discord.py is back
oh great
that's weird docker should log the prints as well
.run print("hello")
.bot
how do i run code
i forgot
{}
.run
.run
print("hello")
!e print("hello")
@sick birch :white_check_mark: Your 3.11 eval job has completed with return code 0.
hello
But you should use #bot-commands for it
no worries
the error was that i forgot the oauth2.. works properly
still weird no errors
like obj not found
With docker you either need to run python via -u or manually set python unbuffered to 1
Also docker logs CONTAINER
get_role(role_id, /)```
Returns a role with the given ID.
Changed in version 2.0: `role_id` parameter is now positional-only.
like:
role = get_role()
role.mention
or you can do <@&role.id>
new in discord.py?
some me what you have done
send me the whole code
oh, you give some "properties" in role?
use the role ids
you can repost that vd, just replace the invite link with <invite link> or something
send me one of your roles id
this is role id 1045875292406808576 ?
embed.add_field(name="1 boost ->", value="<@&1045875292406808576> + pic perms", inline=False)
try this
mentions:
<@&id> roles
<@id> member
<#id> channel
use it as rule!
Integrate your service with Discord — whether it's a bot or a game or whatever your wildest imagination can come up with.
Why wrong
!ytdl
Per Python Discord's Rule 5, we are unable to assist with questions related to youtube-dl, pytube, or other YouTube video downloaders, as their usage violates YouTube's Terms of Service.
For reference, this usage is covered by the following clauses in YouTube's TOS, as of 2021-03-17:
The following restrictions apply to your use of the Service. You are not allowed to:
1. access, reproduce, download, distribute, transmit, broadcast, display, sell, license, alter, modify or otherwise use any part of the Service or any Content except: (a) as specifically permitted by the Service; (b) with prior written permission from YouTube and, if applicable, the respective rights holders; or (c) as permitted by applicable law;
3. access the Service using any automated means (such as robots, botnets or scrapers) except: (a) in the case of public search engines, in accordance with YouTube’s robots.txt file; (b) with YouTube’s prior written permission; or (c) as permitted by applicable law;
9. use the Service to view or listen to Content other than for personal, non-commercial use (for example, you may not publicly screen videos or stream music from the Service)
async def select_callback(self, interaction, select):
#this thing is new in dcpy lastest update in old version it ussed to be first button or other thing then interaction object
u r using classes coooool
what does this mean
#databases please
do u kbonw what it meansa
then wait for their answer ig
nope i dont know
Hello!
I am making a discord bot and I want to track how many people click the button
So like
Say 1 user clicks the button it edits the embed to there mention
And then another user clicks the button it adds another mention to the embed
How would I do somethig like that?
What have you done so far?
async def join_callback(self, inter:discord.Interaction):
joiner = inter.user
number = 0
if number == 1:
await inter.response.send_message(f"**Unfortunatly this lobby is closed.**")
else:
number += 1
join.disabled = True
join.label = str("Join Match 1 (Not Joinable")
await inter.message.edit(view=self)
But for like when 2 peopel can join I want it to display those 2 people
number = 0
if number == 1:
``` 
That if statement is never going to run
You fix that?
?
just incase it doenst
You fix your function?
What?
The function never didn't work?
And also the function isn't done, so yes it will be used
are you kidding us?
I'm asking you about your if statement
