#discord-bots
1 messages · Page 763 of 1
Send the message to the user before banning the user.
ok
it is sending the message before banning them
await member.send(message)
await member.ban(reason=reason)
Seems like you're responding to a timed out interaction or respond twice
Make sure that your autocomplete function is fast enough
why add a reason value when you can add a defualt value in params
(reason="Being bad!")
has a default value of a string
Add the module pip install dnspython
You need help?
Hey does anyone have a great way to implement a discord bot with a website,
the idea is that u click a button on a website to get a specific role on the discord server
in theory you can make a web app send commands to bot, like a web app running along bot. But I'm not sure if that would work 100%
hmm yeah this could work… but i’m looking for more efficient ways tbh
what would be the efficient way?
You could just trigger a function on your discord bot that would be ran when ever you want
how do I trigger a command from a website?
The method I was thinking depends a lot of the way you have the web app designed
the issue is I didn’t design it myself 😖
:/
yeah… well the easiest way would be to send a message in a discord channel using a simple webhook that the discord bot catches and then assigns the role
However im not sure if this can be exploited easily or if it would work 100% of time
gl figuring it out
thx 😵💫
hello. I want to make a command with 2 buttons and when you press the 1st it starts a timer and when click the 2nd it end and gives that time. I know how to make the buttons but no how to start the timer
make the first button take current time, second button take the current time as well (when clicked) and then subtract them
good idea. lemme try it!
👍.
so i did this. ```python
@nextcord.ui.button(label=" ", style=nextcord.ButtonStyle.green)
async def on(self, button: nextcord.ui.Button, interaction: nextcord.Interaction):
user = interaction.user
start_time = time.time()
emb2=nextcord.Embed(title="🟢 On Duty", description=f"{user.mention} Μόλις μπήκες σε υπηρεσία. Πάτα το κόκκινο κουμπί για να βγεις.", color=color, timestamp=datetime.now())
emb2.set_author(name=user.name, icon_url=user.avatar.url)
await interaction.response.send_message(embed=emb2, ephemeral=True)
@nextcord.ui.button(label=" ", style=nextcord.ButtonStyle.red)
async def off(self, button: nextcord.ui.Button, interaction: nextcord.Interaction):
user = interaction.user
end_time = time.time()
time_lapsed = end_time - start_time
emb2=nextcord.Embed(title="🔴 Off Duty", description=f"{user.mention} βγήκες από υπηρεσία. Ο χρόνος που ήσουν online είναι: {time_lapsed}.", color=color, timestamp=datetime.now())
emb2.set_author(name=user.name, icon_url=user.avatar.url)
await interaction.response.send_message(embed=emb2, ephemeral=True)
it worked?
yessss
nice!
Nevermind (sorry for the ping The Lost Programmer)
Why this programm is not working
import telebot
token='xxx'
bot=telebot.TeleBot(token)
keybord1 = telebot.types.ReplyKeyboardMarkup(True)
keybord1.row('1','2')
@bot.message_handler(commands=['start'])
def start_message(message):
bot.send_message(message.chat.id,'Привет')
@bot.message_handler(content_types=['text'])
def send_text(message):
message.text.lower()
if message.text == 'Привет':
bot.send_message(message.chat.id, 'Прив', reply_markup=keybord1)
how do you sense when a new message is entered by a specific user?
sense hmm
how do you code it
wdym by new?
Exactly
bot.wait_for("message", ...)
@bot.command()
@commands.has_permissions(administrator = True)
async def unwarn(ctx, member : discord.Member = None, position = None):
y = json.load(open('warns.json'))
reasons = y[str(member.id)]['reasons']
position -= 1
del reasons[position] ```discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: can only concatenate str (not "int") to str
@jovial storm
I'm trying to pop the reason mentioned out (for example unwarn @rocky trench 1
position seems to be a string
any idea how to fix?
in dpy they ignoring me or sum lol
convert to int
!d disnake.CategoryChannel.is_nsfw
because basic error
is_nsfw()```
Checks if the category is NSFW.
probably
!d disnake.Guild.rules_channel
property rules_channel: Optional[disnake.channel.TextChannel]```
Return’s the guild’s channel used for the rules. The guild must be a Community guild.
If no channel is set, then this returns `None`.
New in version 1.3.
they tend to be less friendly to people who don't bother learning python before making bots
so what would I need to change? I'm a self learnt coder and didnt really use that before
I've observed
I learnt it, i just feel like bc I was helping sum new guys chat was getting spammed away
convert position into int
position = int(position)
ok
!d disnake.StageChannel
class disnake.StageChannel```
Represents a Discord guild stage channel.
New in version 1.7.
x == y Checks if two channels are equal.
x != y Checks if two channels are not equal.
hash(x) Returns the channel’s hash.
str(x) Returns the channel’s name.
the error has left, doesnt do what I want yet tho
class disnake.StoreChannel```
Represents a Discord guild store channel.
x == y Checks if two channels are equal.
x != y Checks if two channels are not equal.
hash(x) Returns the channel’s hash.
str(x) Returns the channel’s name.
i wanted it to pop out the first reason
so I say 1, pops out first
thats why I did position -=1
@bot.command()
@commands.has_permissions(administrator = True)
async def unwarn(ctx, member : discord.Member = None, position = None):
y = json.load(open('warns.json'))
reasons = y[str(member.id)]['reasons']
position = int(position)
position -= 1
del reasons[position] ```
what are you doing lol
trying to remove a warning
some_dict[some_dict.keys()[0]]
del wouldn't do that
if you want to remove it from a database
its json file
Just del the key
yh
@bot.command()
@commands.has_permissions(administrator = True)
async def unwarn(ctx, member : discord.Member = None, position = None):
y = json.load(open('warns.json'))
reasons = y[str(member.id)]['reasons']
position = int(position)
position -= 1
reasons.pop(position) ```
pop is for txt file tho ig?
well it didnt work either
idk what the best approach is but I'd personally remove the warning and then rewrite the json file to contain the edited data
is there a on_message_edit event? and if so what does it return?
wdym?
old and new msg I think
yes there is, it returns a message object I think
'before edit' and 'after edit'
alr
i mean it doesn't return anything, that's for you to do
wut
are you asking about the parameters
reasons.remove(index)
file.write(reasons)
file.close()
not sure what the point is of that
yes
so is it async def on_message_edit(old_message, new_message):?
it removes the warning from the file lol
when you do reasons.remove it doesn't edit the file
it edits reasons
I see
So I need to write it back to the file
yes
But I dont want my entire file to change, just the "reasons"
@bot.command()
@commands.has_permissions(administrator = True)
async def unwarn(ctx, member: discord.Member, position: int):
with open('warns.json', mode='r+') as f:
y = json.load(f)
y[str(member.id)]['warns'] -= 1
del y[str(member.id)]['reasons'][position - 1]
f.write(json.dumps(y, sort_keys=True, indent=4))
not sure but this would replace entire file with it i think
ye, but it would be the same
With the edited y yes.
the only thing different would be reasons
lemme see
And warn amount
That's why i indexed
ye
gay
nice reason
I also don't recommend using json
nah it was testing
As a dutch person i'm very disappointed.
nice reason nonetheless
I support lgbtq+ 😅
jk
its just a joke for my friends lol
ok
now it didnt wipe the file, but added an entire overwrite to it
You mean it appended
Traceback (most recent call last):
File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\runpy.py", line 196, in _run_module_as_main
return _run_code(code, main_globals, None,
File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\runpy.py", line 86, in _run_code
exec(code, run_globals)
File "c:\Users\user\.vscode\extensions\ms-python.python-2021.12.1559732655\pythonFiles\lib\python\debugpy\__main__.py", line 45, in <module>
cli.main()
File "c:\Users\user\.vscode\extensions\ms-python.python-2021.12.1559732655\pythonFiles\lib\python\debugpy/..\debugpy\server\cli.py", line 444, in main
run()
File "c:\Users\user\.vscode\extensions\ms-python.python-2021.12.1559732655\pythonFiles\lib\python\debugpy/..\debugpy\server\cli.py", line 285, in run_file
runpy.run_path(target_as_str, run_name=compat.force_str("__main__"))
File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\runpy.py", line 268, in run_path
code, fname = _get_code_from_file(run_name, path_name)
File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\runpy.py", line 237, in _get_code_from_file
with io.open_code(decoded_path) as f:
FileNotFoundError: [Errno 2] No such file or directory: 'c:\\Users```
what is this error ?
@bot.command()
@commands.has_permissions(administrator = True)
async def unwarn(ctx, member: discord.Member, position: int):
with open('warns.json', mode='r+') as f:
y = json.load(f)
y[str(member.id)]['warns'] -= 1
del y[str(member.id)]['reasons'][position - 1]
f.truncate(0)
f.write(json.dumps(y, sort_keys=True, indent=4))
btw, for the check i recommend changing it to @commands.has_permisions(view_audit_log=True)
yh this works, but it spams smthng in my file
nul nul nul
i've never seen that happen before
me neither lol
Open it in a normal text editor
but the file is json
I would need to change everything in my scripts?
no
just open it in notepad
Then just ignore that
vscode is strange
json is strange
programming in general is strange
for ME, if i ran a print statement of a json_file.read(), the json file apparently wasn't set, that's just messed up (even tho i did set it)
is there also a way to wipe all 'reasons' at once?
This code in SQL would only take one line ```sql
DELETE FROM warnings WHERE warning_id = id
y[str(member.id)]['reasons'] = []
@bot.command()
async def clearwarns(ctx, member : discord.Member = None):
with open('warns.json', mode='r') as f:
y = json.load(f)
y[str(member.id)]['reasons'] = []
y[str(member.id)]['warns'] -= y[str(member.id)]['warns']
f.truncate(0)
f.write(json.dumps(y, sort_keys=True, indent=4))```
would this do it? imma have to add if .. is none too now
I got no idea
@bot.command()
async def clearwarns(ctx, member : discord.Member = None):
with open('warns.json', mode='r') as f:
y = json.load(f)
y[str(member.id)]['reasons'] = []
y[str(member.id)]['warns'] = 0
f.truncate(0)
f.write(json.dumps(y, sort_keys=True, indent=4))
isnt it the same tho lol
y[str(member.id)]['warns'] -= y[str(member.id)]['warns'] dunno why you did this long method
idk xd
hello. Sorry for the interupting. I have this code but i get this error ```python
@nextcord.ui.button(label=" ", style=nextcord.ButtonStyle.green)
async def on(self, button: nextcord.ui.Button, interaction: nextcord.Interaction):
user = interaction.user
start_time = time.time()
emb2=nextcord.Embed(title="🟢 On Duty", description=f"{user.mention} Μόλις μπήκες σε υπηρεσία. Πάτα το κόκκινο κουμπί για να βγεις.", color=color, timestamp=datetime.now())
emb2.set_author(name=user.name, icon_url=user.avatar.url)
await interaction.response.send_message(embed=emb2, ephemeral=True)
@nextcord.ui.button(label=" ", style=nextcord.ButtonStyle.red)
async def off(self, button: nextcord.ui.Button, interaction: nextcord.Interaction):
user = interaction.user
end_time = time.time()
time_lapsed = end_time - start_time
emb2=nextcord.Embed(title="🔴 Off Duty", description=f"{user.mention} βγήκες από υπηρεσία. Ο χρόνος που ήσουν online είναι: {time_lapsed}.", color=color, timestamp=datetime.now())
emb2.set_author(name=user.name, icon_url=user.avatar.url)
await interaction.response.send_message(embed=emb2, ephemeral=True)
NameError: name 'start_time' is not defined
start_time = time.time() can't be accessed outside the function
you could use self.start_time = ... which should work, but I'm not sure
how would I go about making an invite checker?
I'm aware of guild.invites() but could I use member.guild.invites()?
okay so it worked
but i want to split it ine hours:mins:sec
Can't run discord.py via VS code
i try reinstall python still got this message:
Python was not found; run without arguments to install from the Microsoft Store, or disable this shortcut from Settings > Manage App Execution Aliases.
Take a look at strftime
That is nice for formatting datetime strings
@cloud dawn
my warn command doesnt work anymore for sum reason
@bot.command()
@commands.has_permissions(administrator = True)
async def warn(ctx, member : discord.Member = None, *, reason = None):
y = json.load(open('warns.json'))
if member ==None:
embed = discord.Embed(
title = '**Error**',
description = 'Please provide a member to warn!',
color = (0x3498db)
)
return await ctx.send(embed=embed)
if reason == None:
if str(member.id) in y:
y[str(member.id)]["reasons"].append('Unknown')
y[str(member.id)]['warns'] +=1
print(y)
json.dump(y, open('warns.json','w'), indent = 4)
embed = discord.Embed(
title = '**Warned**',
description = f'Succesfully warned {member}',
color = (0x3498db)
)
embed.add_field(name = '**Reason:**', value = 'unknown', inline = False )
await ctx.send(embed=embed)
else:
y = json.load(open('warns.json'))
y[str(member.id)] ={"warns": 1, "reasons": ['Unknown']}
print(y)
json.dump(y, open("warns.json",'w'), indent = 4)
embed = discord.Embed(
title = '**Warned**',
description = f'Succesfully warned {member}',
color = (0x3498db)
)
embed.add_field(name = '**Reason:**', value = 'unknown', inline = False )
await ctx.send(embed=embed)
else:
if str(member.id) in y:
y[str(member.id)]["reasons"].append(reason)
y[str(member.id)]['warns'] +=1
json.dump(y, open('warns.json','w'), indent = 4)
embed = discord.Embed(
title = '**Warned**',
description = f'Succesfully warned {member}',
color = (0x3498db)
)
embed.add_field(name = '**Reason:**', value = reason, inline = False )
await ctx.send(embed=embed)
else:
y = json.load(open('warns.json'))
y[str(member.id)] ={"warns": 1, "reasons": [reason]}
json.dump(y, open("warns.json",'w'), indent = 4)
embed = discord.Embed(
title = '**Warned**',
description = f'Succesfully warned {member}',
color = (0x3498db)
)
embed.add_field(name = '**Reason:**', value = reason, inline = False )
await ctx.send(embed=embed)```
it used to work
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: JSONDecodeError: Expecting value: line 1 column 1 (char 0)
its bc of the nul nul 100%
so i changed self.start_time = now.strftime("%H:%M:%S") and self.end_time = now.strftime("%H:%M:%S")
but i get this error
TypeError: unsupported operand type(s) for -: 'str' and 'str'
hello
can someone help me with this problem in discord.py
@bot.command()
async def insult(ctx):
async with aiohttp.ClientSession() as session:
request = await session.get('https://evilinsult.com/generate_insult.php?lang=en&type=text')
insultjson = await request.json(content_type='text/html')
await ctx.send(url=insultjson['insult'])
I recommend using strftime only for the output after you substract, currently strftime returns 2 strings
like this?? ```python
self.time_lapsed = self.end_time - self.start_time
self.end = self.time_lapsed.strftime()
what's the issue
!d disnake.Message.delete
await delete(*, delay=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Deletes the message.
Your own messages could be deleted without any proper permissions. However to delete other people’s messages, you need the [`manage_messages`](https://docs.disnake.dev/en/latest/api.html#disnake.Permissions.manage_messages "disnake.Permissions.manage_messages") permission.
Changed in version 1.1: Added the new `delay` keyword-only parameter.
Try it and see, remember to add format string inside strftime function
it says error
send it along with sample json
why the heck this aint working? ```py
@commands.command()
@commands.is_owner()
async def changenick(self, ctx, *, nickname):
print("Changing nick on bot.")
await ctx.guild.me.edit(nick=nickname)
i changed it like this ```python
self.time_lapsed = self.end_time - self.start_time
self.end = self.time_lapsed.strftime("%H:%M:%S")
``` AttributeError: 'float' object has no attribute 'strftime'```
oh it sais i dont own the bot
Ok so it returns a float...
I can't really help any further but I suggest asking the time and strftime in #python-discussion
okay ty
5. Do not provide or request help on projects that may break laws, breach terms of services, or are malicious or inappropriate.
!rule 1
1. Follow the Python Discord Code of Conduct.
guys explain to me why:
owner_id=os.getenv("IRL_OWNER") has my id but refuse
@commands.command()
@commands.is_owner()
async def changenick(self, ctx, *, nickname):
print("Changing nick on bot.")
await ctx.guild.me.edit(nick=nickname)
suddenly stopped
my .env == IRL_TOKEN=<censored> IRL_OWNER=<censored but correct>
Are you the owner of bot account?
sorry for bothering you again. I have this command, it works but i want to make it like refresh every one min so it can update the status. Do you know how?? ```python
em = nextcord.Embed(title=':green_circle: Server Is Online!', description=f"Για να συνδεθείτε στον {name}Ανοίγεται FiveM, πατάτε F8 και γράφεται connect {ip}:{port}", color=orange, timestamp=datetime.now())
em.set_author(name=name)
em.add_field(name = 'Online Playes:', value= str(events['clients'])+"/"+str(events['sv_maxclients']), inline = True)
em.add_field(name = 'Server Ip:', value= f"{ip}:{port}", inline = True)
await ctx.send(embed=em)
commandscha = self.client.get_channel(int(config['commandslogs']))
user10 = ctx.author
user = ctx.author
channel10 = ctx.message.channel
prefix10 = config["prefix"]
emb6=nextcord.Embed(title="New Commands Use!", description=f"", color=orange, timestamp=datetime.now())
emb6.set_author(name=user.name, icon_url=user.avatar.url)
emb6.add_field(name="User: ", value=f"{user10.mention}")
emb6.add_field(name='Channel: ', value=f"{channel10.mention}")
emb6.add_field(name='Command: ', value=f"{prefix10}status")
await commandscha.send(embed=emb6)
Sorry, I'm not able to help atm
Create a task
how can i??
!d discord.ext.tasks.loop
discord.ext.tasks.loop(*, seconds=..., minutes=..., hours=..., time=..., count=None, reconnect=True, loop=...)```
A decorator that schedules a task in the background for you with optional reconnect logic. The decorator returns a [`Loop`](https://discordpy.readthedocs.io/en/master/ext/tasks/index.html#discord.ext.tasks.Loop "discord.ext.tasks.Loop").
Quick question if Discord.py has been archived and doesn't support / cmd's what do people use?
!pypi disnake
Thank You!
!d discord.Role.delete
await delete(*, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Deletes the role.
You must have the [`manage_roles`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.manage_roles "discord.Permissions.manage_roles") permission to use this.
does the role exist?
Show your code
The topmost role is the everyone role and cannot be deleted
List indexing
Skip the everyone role with list indexing
If you're wondering how
ctx.guild.roles returns a list of the roles
You can, do [1:] to ignore the everyone role
No
Its there
Hehe
This is the owner of the server
Welcomeeee
Of the bot*
`Nah
No?
"This is not the owner of the server"
!d discord.ext.commands.is_owner
@discord.ext.commands.is_owner()```
A [`check()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") that checks if the person invoking this command is the owner of the bot.
This is powered by [`Bot.is_owner()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot.is_owner "discord.ext.commands.Bot.is_owner").
This check raises a special exception, [`NotOwner`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.NotOwner "discord.ext.commands.NotOwner") that is derived from [`CheckFailure`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure").
Woah, I thought I was too dumb and read the docs wrong ;-;
Ye owner of bot
Welp
oh ok
but bot runs as normal
sorry i didnt now
kek
cuz always when i tested it did cuz i was owner of the guild and the bot
Its clearly proved you inferior
You saw?
You have no respect even your own bot humiliates you 
Lmao, jk, dont take it seriously
Use the isinstance function
Idk about announcements, but you can check for sytem channels, text channels and voice channels and nsfw channels using the isinstance method
soo
nextcord.utils.get(ctx.guild.channels, name="channel name")
``` this @cedar smelt
so like```py
nextcord.utils.get(ctx.guild.channels, name="rukes")
Fetching channels is way better, or just use the get_or_fetch method
and what does that mean?
@cedar smelt i dont get what your trying to do
oh
like this?
like a database is needed i think
code = "".join(random.choices(string.ascii_uppercase + string.digits + string.ascii_lowercase,k=16))
return f'{passwort}' ```
How to fix this? i wanna use this in a ctx message
@client.command()
async def restore(ctx):
guild = ctx.guild
RulesChannel = await guild.create_text_channel(name="Rules")
``` @cedar smelt
something like this
dont use a function do it in your command so like:
@client.command()
async def nitro(ctx):
code = "".join(random.choices(string.ascii_uppercase + string.digits + string.ascii_lowercase,k=16))
await ctx.reply(code)
how do you check for roles in a user?
how can i freeze all channels in a server?
!d discord.Member.roles
property roles: List[Role]```
A [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.9)") of [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role") that the member belongs to. Note that the first element of this list is always the default [‘@everyone](mailto:'%40everyone)’ role.
These roles are sorted by their position in the role hierarchy.
tutorial
tutorial
bit unneccesary but sure
ty verry much
yes but you wanna fix errors here for full commands you should watch tutorials
I got ignored as usual
I literally told you what method to use.....
I wouldn't be here if i found anything online or in the docs.
Wdym by freeze?
Hey!
Thanks for watching todays video, todays video I really hope you enjoyed and join my discorddd :) Also thank you SO MUCH for 1350 subscribers!!
LINKS -
Join my Discord - https://discord.gg/twHW4UUJGq
Nextcord Server - https://discord.gg/Ucmae5Kbwb
Set Up VSC - https://www.youtube.com/watch?v=KpzkP...
Set Up PYTHON - https://youtu.be/h4...
Like the silence command here
Not helpful
Sorry. Basically what silence does here is remove send_messages permissions from every channel. I have code that works for the channel the command is sent in but trying to recycle that could with a for loop didnt work.
@forest beacon this not helpful
Dude its an 8 minute video.
so?
Coding takes time man
Iterate thru guild.channels and use channel.set_permissioms
I havent made it through it. Im not meteor man.
async def freeze_all(self, ctx):
channels = ctx.guild.channels
for channel in channels:
print(channel)
await ctx.channel.set_permissions(ctx.guild.default_role, send_messages=True)```
@knotty gazelle Stop
Misguiding
Try
To
HELP
this is it
Doesn't work
This changes the perms.for the everyone role for all channels
Not for other ones
Thats what i need. currently no one has roles so theoretically it should work
send_messages needs to be False
you are setting the permissions to trie
True*
That means u r giving them the perm
I copied the wrong function. Thank you lmao
Your Welcome
!d discord.Guild.system_channels
Changed that, only works for the channel it was sent in.
If that was it?
!d discord.Guild
class discord.Guild```
Represents a Discord guild.
This is referred to as a “server” in the official Discord UI.
x == y Checks if two guilds are equal.
x != y Checks if two guilds are not equal.
hash(x) Returns the guild’s hash.
str(x) Returns the guild’s name.
oh this works not as Mr.Danny 😅
!d discord.TextChannel.is_nsfw
is_nsfw()```
[`bool`](https://docs.python.org/3/library/functions.html#bool "(in Python v3.9)"): Checks if the channel is NSFW.
Click on it , it will take u to all other checks
discord.Guild
Ow
!d discord.Guild.system_channel
property system_channel: Optional[discord.channel.TextChannel]```
Returns the guild’s channel used for system messages.
If no channel is set, then this returns `None`.
Welp
Yes this it
Thats it right?
Indeed
y?
Huh?
Why what?
It was very useful right or is my nick right>
Nick seems right
you're misleading
Welcome
What's the point to joining the string lol , it returns the same thing
!e print("".join("loser"))
cool coders 2022
yes but it means im more a loser cuz its more advanced
Ahan
🙂
Suits me
Javascript guy?
It's rust
oh lol
if a message contains a link like @joe, i found an exploit in the snekbox, here it is https://www.youtube.com/watch?v=dQw4w9WgXcQ how to i find and pull just the link from it?
!ot coughs
@cloud dawn, Ask from mature people 
prolly check all the words and only save that that contains https://, or any link stuff
Regex?
WHAT
Dia how are you a programmer and you don’t know what regex is.
Lol I thought they were joking-
it's a he
what's regex
well, I'm gonna google it
How do I spell it 😔
He learned d.py before actually learning python. So you know. It do tend to be that way.
yes, I did
Welp
regex is a built in
I had to install it welp
Idk then. It’s part of pythons standard package library.
bad at regex
I didn't even know what it is, yet I can do what I want in programming anyways
But-
Mhm
Lol its fine, your convenience
and I know most about dpy so that's why I'm here
hello gentlemen
hi
i'd have a question,
i want my bot to send a message to a specific channel where the user used that command.
I'm using / commands and the discord-py-slash-command library, and it's a kick command.
async def kick(ctx:SlashContext, user, reason:str = "None"):
await user.kick()
await user.send(f"Kicked from {ctx.guild.name} for {reason}")
kicked = user.mention
embed = discord.Embed(title = "Kicked a user", description = f"Kicked {kicked} for reason: {reason}")
await ctx.send(embed)
print(f"{user} used: kick")
this should kick the user (which it does) and then send a message in the chat where the command was used (which it does NOT)
perhaps i could associate the channel to a variable beforehand, but as i'm new to this i'm kinda lost
Typehint the user to discord.Member
await ctx.send(embed=embed) is how it's used everywhere else
embed is not a positional argument indeed
no
It’s optional.
print(f"{user} used: kick") is just kicking my eyes
oof
what do you mean sir with typehint?
i copied it online, for now i want to understand the concept and then perfectionate it, sorry
I'm not a sir-
Typehinting in python
await user.send(f"Kicked from {ctx.guild.name} for {reason}")``` switch these two lines
they might cause an error
if you won't have a shared guild with this person anymore, you can't send a message to him
so send before kick
Oh yeah, the user will be none
Or
oh yes that's my problem, and that fixes it, i don't know how i haven't thought about it before..
;-;
Welcome
sorry sir
i am just used to calling everyone sir ma'am
thank you both anyway
Welp,welcome
that's kinda nice
it's for respect, especially here since i'm speaking with more knowledgeable people
i have one problem now
Mhm go ahead
in the terminal it says "<the name of the kicked user> used: kick"
it's supposed to say the name of the person issuing the command
here is how i changed the code:
async def kick(ctx:SlashContext, user, reason:str = "no reason nerd XD"):
await user.send(f"Kicked from {ctx.guild.name} for {reason}")
await user.kick()
kicked = user.mention
embed = discord.Embed(title = "Kicked a user", description = f"Kicked {kicked} for reason: {reason}")
await ctx.send(embed = embed)
print(f"{user} used: kick")
how can i address the user using the command instead?
print(f"{ctx.author} used: kick")
author
yes
thank you, i will have to remember these things
could you tell me the specific meaning of ctx?
!d discord.ext.commands.Context
class discord.ext.commands.Context(*, message, bot, view, args=..., kwargs=..., prefix=None, command=None, invoked_with=None, invoked_parents=..., invoked_subcommand=None, ...)```
Represents the context in which a command is being invoked under.
This class contains a lot of meta data to help you understand more about the invocation context. This class is not created manually and is instead passed around to commands as the first parameter.
This class implements the [`Messageable`](https://discordpy.readthedocs.io/en/master/api.html#discord.abc.Messageable "discord.abc.Messageable") ABC.
docs 😄
ooo i should have checked the docks 🤦♂️
thanks again, sorry for bothering for such simple things but i am still learning
you're welcome
!d discord
To work with the library and the Discord API in general, we must first create a Discord Bot account.
Creating a Bot account is a pretty straightforward process.
Just curious in NodeJs there was a .on - when the bot was running does such a command exist with disnake?
how do i get all the cog names?
help([object])```
Invoke the built-in help system. (This function is intended for interactive use.) If no argument is given, the interactive help system starts on the interpreter console. If the argument is a string, then the string is looked up as the name of a module, function, class, method, keyword, or documentation topic, and a help page is printed on the console. If the argument is any other kind of object, a help page on the object is generated.
Note that if a slash(/) appears in the parameter list of a function when invoking [`help()`](https://docs.python.org/3/library/functions.html#help "help"), it means that the parameters prior to the slash are positional-only. For more info, see [the FAQ entry on positional-only parameters](https://docs.python.org/3/faq/programming.html#faq-positional-only-arguments).
This function is added to the built-in namespace by the [`site`](https://docs.python.org/3/library/site.html#module-site "site: Module responsible for site-specific configuration.") module.
!d discord.Message
class discord.Message```
Represents a message from Discord.
x == y Checks if two messages are equal.
x != y Checks if two messages are not equal.
hash(x) Returns the message’s hash.
what do you guys use since discord.py discontinued
!pypi disnake
I am new but this is what someone recommend so I am going to use it.
Hey @tough bobcat!
You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.
argh
I have the
@bot.event
async def on_command_error(ctx, error):
set to dm me when an error is raised, but i am getting the attatched error logged to the console instead of going into the event function
https://paste.pythondiscord.com/erenijoqov.sql
can you invoke a command within on_message event?
invoke is only based around context but how can i gain context within on_message
nvm
I was gonna say
Bot.get_context(Message) exists.
I got pinged?
i smell regex
just send it to the member
you can use ctx.author
no i mean it works for normal errors like just doing
@bot.command(name='div0')
async def _div0(ctx):
# type: (commands.Context) -> None
1/0
but for this other error it just doesnt work
it’s -> None:
Any reason why you do the type in a command rather than the actual signature itself, E.g ```py
async def _div0(ctx: commands.Context) -> None: ...
Backwards compatibility I assume?
Also your error you sent in the hastebin has something to do with your network configurations? Or the network security configurations either or not sure
!d disnake.abc.Messageable.send
await send(content=None, *, tts=None, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, ...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Sends a message to the destination with the content given.
The content must be a type that can convert to a string through `str(content)`. If the content is set to `None` (the default), then the `embed` parameter must be provided.
To upload a single file, the `file` parameter should be used with a single [`File`](https://docs.disnake.dev/en/latest/api.html#disnake.File "disnake.File") object. To upload multiple files, the `files` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.10)") of [`File`](https://docs.disnake.dev/en/latest/api.html#disnake.File "disnake.File") objects. **Specifying both parameters will lead to an exception**.
To upload a single embed, the `embed` parameter should be used with a single [`Embed`](https://docs.disnake.dev/en/latest/api.html#disnake.Embed "disnake.Embed") object. To upload multiple embeds, the `embeds` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.10)") of [`Embed`](https://docs.disnake.dev/en/latest/api.html#disnake.Embed "disnake.Embed") objects. **Specifying both parameters will lead to an exception**.
Can you set the channel and guild? To send the message in. - Thanks.
Just channel/guild.send
So - Discord.JS is where I am coming from - to define a specific guild by ID you would do something like
global.guild = await discordClient.guilds.fetch("834851020524748840", true, true);
``` Do you know if there is a python equivalent - I know how to set it as a global | just I don't know the specifics for getting it to set the guildID.
bot.get_guild(id) this perhaps
there's also a fetch equivalent
Gotcha - Did you just find this in the documentation?
!d disnake.ext.commands.Bot.getch_user
await getch_user(user_id, *, strict=False)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Tries to get the user from the cache. If fails, it tries to fetch the user from the API.
I had to look up the exact name in the docs, yes
Yeah - I don't want the user - ultimately I want to be able to send a message to a specific channel
Thx. Bones.
my understanding is that fetch would send an api request to get the id, and get would look for it in the cache. In what cases is each applicable?
It says here that For general usage, consider get_guild(), though I would have thought it'd be the opposite
When would the id not be in the cache?
True
Well that's more because of the design patterns of discord.py
Hikari (a much better python discord lib) can work without a cache so fetching is recommended there
Okay - clearly this is going way over my head - if I want to message a specific channel in a guild - how would I go about doing that - in Python?
You don't need the guild to send a message
^
The API just needs the channel id
Oh - really. Thats easier.
hikari.RESTClient.create_message(channel_id, "content") if you're using a good library
Otherwise you gotta get a partial messagable or fetch the channel with dpy
channel = bot.get_partial_messageable(channel_id)
await channel.send("content")
all you need is ctx.channel
Ain't it true tho, hikari is so much better than dpy with working with partial data
yeah it is but some dpy forks are great too
Yeah if you're sending to the same channel, that doesn't seem to be what they specifically asked for
Yeah I'm one of the core devs of disnake actually
Yeah
nice
what wrapper are you using. Discord.py?
I don’t actually use disnake, I use nextcord but I have heard disnake is great
in dpy you would need the channel object iirc
2.0 feature
Just use that
but I found this new discord api wrapper. It isn’t a fork of dpy and has stuff like middleware (you can customize it)
!pypi pincer
dpy kinda sucks with this though 😔
I was using - disnake | all I need is to be able to message to specific channels and do / cmd's
Guess what lib has that too, hikari
Pincer is still in alpha and planning phase
use hikari mate
I’ll check it out
mainly got my eyes on pincer rn doh
but it’s good to know multiple libs
Yeah the partial messagable should do the trick if all you need to do is send a message
where are you getting a partial massageable from?
Yeah pincer looks cool, there are just some questionable design patterns atm so imma give it a while to mature
It's just a dummy object with a channel id to process sending messages
where from
Build it with a bot method
yea def. I’m currently making like a simple bot with it and messing around with it so I can see how it works
but def won’t make a production bot with it yet
!d discord.TextChannel.get_partial_message
get_partial_message(message_id, /)```
Creates a [`PartialMessage`](https://discordpy.readthedocs.io/en/master/api.html#discord.PartialMessage "discord.PartialMessage") from the message ID.
This is useful if you want to work with a message and only have its ID without doing an unnecessary API call.
New in version 1.6.
Wait
Yeah nvm then
Damn this server needs some slash commands god damn
It's not a partial message tho
what's the diff between this and get_channel
How is partial messageable able to send a message when it calls for a an id of a message
get_channel uses the cache to get full channel data
get_partial_messageable creates a dummy object with just the id
Both can be used to send messages
PartialMessage has a .channel attribute there. You can use .send() on that
It uses an id of a channel
How so? Slash commands are very under powered compared to regular commands... If this server switched to slash commands for an example one command such as eval would be completely eradicated. This bot is also not gonna get verified as It's only for this guild, no point
Not partial message. Nothing to do with partial messages. I'm talking about partial messageables
I miss my autocomplete
And yeah stuff like eval will probs have to stay as a prefix command for now, that's unavoidable
Unless discord adds multiline support which a lot of us have been asking for. I doubt they would deliver though
Didn't we already get a preview for it
And if multiline options don't come first we'll at least have modals
The text input components?
Yup
Though eval still seems better as a prefix command even for its more niche features like rerunning code on message edit n stuff
global channelBeta1 ; await bot.get_partial_messageable("883737072454750269")
channelBeta1.send()``` - Pretend the second line is in another file - this should work right? | then I can just follow the (https://discordpy.readthedocs.io/en/master/api.html#discord.abc.Messageable.send)
Sure, but slash commands are still very young and under-powered compared to "regular" chat commands. It's gonna be hard to make up that huge difference
don't forget to await .send()
One of the main reasons from discord at least is adding slash commands would make it easier for developers
When in-fact slash commands have quite a layer of complexity behind them, depending on the user of the API.
Although API wrappers can just make simple builders for said commands the implementation is humongous
I don't understand the partial_messageable approach. I would use get or fetch channel with your channel id
Honestly I'm just glad there's some standardization now
Not well designed for python styled libraries, clearly aimed for javascript
Just py bot.fetch_channel | instead and then await it.
This is what discord.py does to you man
Oh yeah they can, have you seen hikari's approach on this?
I'm all ears
No not at all, designing my own wrapper so I want to be un-biased
Errr, not designing anymore just rewriting my previous almost completed one
discord.py's design patterns encourage working with full data even when it would be at the price of several more API fetches
A notable example here is the fact you are for some reason encouraged to fetch a full channel object when all you need is the id to make a request for sending a message
Gotta respect that
discord.py also pretty much has outdated code, I have yet to see a lot of refactors
Yup definitely
I'll have a look at this hikari later
So much better man
Thanks means a lot, but my motivation is also wavering a bit
My old wrapper was basically from scratch wrapper with discord.py semantics
But now my new rewrite is different from discord.py semantics
Going good so far I'd say
while hikari has less abstraction it also has a lot of less questionable code. discord.py is already starting to fall apart with the new features
for example banners not being present on user objects in cache
That one's a whole lotta fun to debug I bet
dpy is fun because the ridiculous amount of try/excepts all around the project ensure that everything works no matter what
Even when it means it won't work as intended
The horrors one has to go through to maintain a fork
Hikari's a project I look up to and I actively try to steer disnake in such a way so we can become more like hikari
Mmmm I've never understand maintaining a fork
Honestly, some things are just meant to die
I'd much rather create from scratch. I'd be more familiarised with the codebase, as I wrote it myself
Along with code chocies
I learned a lot about signature parsing while working at disnake though
Wrote shitty code for disnake so I could later write pretty code for hikari
Signature parsing? Is this for commands
yeah, disnake's slash commands
I was the one who designed them
I tried to make it resemble the familiar dpy commands while following fastapi semantics
Compare and contrast with my old slash commands parser? I need more inspiration as my rewrite wrapper will be fully native, thus not using commands-extension
Oh actually nevermind, I'll just rewrite the slash command parser from scratch
I need help
@bot.command()
@commands.has_permissions(kick_members=True)
async def kick(ctx, member: discord.Member, *, reason=None):
await member.kick(reason=reason)
embed = discord.Embed(color=color, description=f'{member} was kicked')
await ctx.send(embed=embed)
@kick.error
async def kick_error(ctx, error, member: discord.Member):
if isinstance(error, commands.MissingPermissions):
embed = discord.Embed(color=color, description=f'{member} You do not have the permission to use this command')
await ctx.send(embed=embed)```
The kick error message is not sending
mmmm I def do not like the identical implementation every fork as right now
someone pls help me 😭
can someone help me fix the kick error message
The modern way is a poorly designed way that only allows for more space to be taken up in my opinion
If this is the "modern" way, the forks def need a rework
Poorly designed that is depending on the fork itself
I'm mostly talking about the decorators, etc
Its quite obvious an attempt to stick with the old commands format
but that won't be scalable for larger commands
-
pycord - places metadata into annotations making it impossible to use mypy (LOVE IT!)
-
nextcord - little features, all metadata in defaults
-
disnake - everything discerned from a valid annotation, descriptions taken from docstrings
-
edpy (draft) - classes with an options attribute for raw option data and a callback method
-
d-interactions - option parameter in decorators for raw option data
-
hikari-tanjun - decorator chains
-
hikari-tanchi - signature parsing same as disnake (cause I did both lmao)
There's diversity alright
Mmmm time to switch from mypy tbh. Pyright has a strict flag and I've been using it after switching from mypy
The maintainer of pyright is quite fast and professional
Mypy doesn't even support Self in annotations
Mypy has a strict flag too idk what you're talking about
He left my issue open for a month now 😭
Was it for a reason or just randomly?
Idk
Lemme send it
Issue is fixed when using a venv btw
Because the site package wouldn't be there
But that's such an annoying detail
But where you not using a venv before?
I used to not use a venv
I have been forced to because of this bug though
I kinda never bothered to tbh
At least it's a good practice to use a venv when developing
Yeah it is but I never had an actual need for it
Didn't have any conflicting dependencies because I kept everything up-to-date
I'm sure it would've been useful in places. You would basically ensure your wrapper usable in the way you use it, python version control, package control, python directory cleanliness
Quite a lot of stuff
I could not develop well without my poetry environment
Also includes building packages in itself, no need for all that building manually
Python version control is so damn messy man, there needs to be some actual standard instead of a lot of backwards compatible nonsense
There is a standard, use a VENV and ensure the compatible python versions
Gotta switch to 3.10 at some point
pyproject.toml lines 13 to 16
[tool.poetry.dependencies]
python = "^3.9"
aiohttp = "^3.8.1"
typing-extensions = "^4.0.1"```
I accidentally switched to 3.10 😔 It automatically updated when I did pacman -Syu and I wasn't prepared for it
Worst thing about pinning dependencies is that I gotta remember to update them 💀
Github dependabot
The PRs are quite floody though
Yeah I've unfortunately noticed
Ah shit, rip discord.py
i did it once and pylance had a stroke
so im in 3.9.9
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "main.py", line 172, in help
await ctx.send("Testing selects for help command!",embed=embed_hm,view=view)
TypeError: send() got an unexpected keyword argument 'view'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 1353, in invoke
await super().invoke(ctx)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: send() got an unexpected keyword argument 'view'```
@slate swan
I was
It was working before
What version are you on?
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.
New in version 2.0.
Ok
What are these callef?
buttons
!d discord.ui.Button
class discord.ui.Button(*, style=<ButtonStyle.secondary: 2>, label=None, disabled=False, custom_id=None, url=None, emoji=None, row=None)```
Represents a UI button.
New in version 2.0.
its a class @zealous dagger
whats your lib?
youll need 2.0
How do I update?
Use a fork , or clone the master branch
the repo has info
You'd need git for that
Alright
yeah i recommend a fork tbh
Hmm
forks have slash commands
Let me open the link
not all
which
yes , but forks like Disnake and nextcord have slash commands and are recommended
your friends fork doesnt count lol
It's looks the same
thats hat i said
The BOT example
Disnake's slash commands implementation are older than other libraries since it's similar to dislash.py lmao ( the developer is Same)
pardon but i know nothing bout disnake i tried getting the server link of it but cudnt get it
ooo
nextcord > disnake
What do I do here?
cant compare
not replit ohb no
For me , it's hikari>forks
true
ty
@slate swan
i want to try hikari ngl
nothing , just use hit to install the library
for giving link
You're welcome
imma try hikari also, but pincer is promising, wathc out for it
whats ur bots name btw
well ,I tried hikari and it's really better in speed and cache features than dpy
Kakashi,that's the only public bot I have
:o
hi
ok
!resources
is_news()```
[`bool`](https://docs.python.org/3/library/functions.html#bool "(in Python v3.9)"): Checks if the channel is a news channel.
yep
they can
!d discord.Guild.edit
await edit(*, reason=..., name=..., description=..., icon=..., banner=..., splash=..., discovery_splash=..., community=..., region=..., afk_channel=..., owner=..., ...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Edits the guild.
You must have the [`manage_guild`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.manage_guild "discord.Permissions.manage_guild") permission to edit the guild.
Changed in version 1.4: The rules\_channel and public\_updates\_channel keyword-only parameters were added.
Changed in version 2.0: The discovery\_splash and community keyword-only parameters were added.
Changed in version 2.0: The newly updated guild is returned.
community kwarg
create_text_channel
!d discord.Guild.create_text_channel
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...
Where's the news kwarg
using channel.edit py edit(type=ChannelType.news) should work too right?
Weird... Imagine making two API Calls 
yea
ch = await Guild.create_text_channel(name='name')
await ch.edit(type=ChannelType.news)
it works , im not sure if there's any other way of doing that with a single request
https://discord.com/developers/docs/resources/guild#create-guild-channel
The type parameter exists in docs tho @slate swan
Integrate your service with Discord — whether it's a bot or a game or whatever your wildest imagination can come up with.
lemme try with an eval using create_text_channel
Thanks
await _ctx.guild.create_text_channel(name='test' , type=disnake.ChannelType.news)
TypeError: Guild.create_text_channel() got an unexpected keyword argument 'type'
discord/guild.py line 1095
name, overwrites=overwrites, channel_type=ChannelType.text, category=category, reason=reason, **options```
see the message below that codeblock
i dont see a reason to do that , like they could set the default value to ChannelType.text and allow using ChannelType.news with the channel_type kwarg
yes , it works
Ikr
Also why set it to None/MISSING first in the function definition and then use if statements??? I don't know why devs don't set it directly
Sure
yep , it needs to be TextChannel obj
Lol
Can't you just select the channel to edit by ID?
nope
fair enough thanks
You know... When I was making the private wrapper for revolt, I was thinking... Why not associate every method with the bot or the ctx object... Like bot.send(channel-id, *args, **kwargs and so on haha... You know, associate everything with the IDs itself. No need for the objects lol
hikari does something similar :p
Hahaha
await BotApp/GatewayBot.rest.create_message(channel_id, content, ...)```
I never looked into that tbh...
well im sure d.py's http client has that
I just think getting and fetching objects is just useless and wastes resources (though negligible)
You could do that, but what happens to data you receive from the websocket? Unless revolt doesn't have a websocket
some of the requests needed the object
Not really
and that's to make the wrapper cleaner
The objects is just library abstraction
You can make the request entirely with IDs and payloads, that being the case of discord.py
It has one
Yea, so then it would be a good idea to make objects
Hmm well I did make them afterwards ngl
Unless you inject the object into a caching layer of the bot
what if you provided a wrong id , just a request failure
by get/fetch u actually know that the object with that id exists or not
Hmm
If the ID doesn't exists it raises an error
Thus the opposite means an ID exists
Unless that was what you meant
😔
yea but that would still be a request right? altho a failed one
Sure, but that requests bucket will fill up pretty quickly depending on the X-Ratelimit-reset-after
Anyways most of the objects in discord.py are from the gateway
As you receive most things through it such as members from GUILD_CREATE payloads
rules_channel=None
Not directly the object's class, but for example https://discord.com/developers/docs/resources/channel#modify-channel permission_overwrites accepts "array of overwrite objects" and discord.py PermissionsOverwrites has as_dict or to_dict method. So probably there are some method which really need you to get the object.
a community guild without rules channel?/
No, just create the dict yourself
Nothing here on objects is required
It's all library abstraction
yeah but why create your own dict if discord.py already has a method to convert it to dict
whats that
what library are you using
and its an event
!d disnake.Guild.create_scheduled_event
await create_scheduled_event(*, name, scheduled_start_time, entity_type, privacy_level=..., channel_id=..., entity_metadata=..., scheduled_end_time=..., description=..., reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Creates a [`GuildScheduledEvent`](https://docs.disnake.dev/en/latest/api.html#disnake.GuildScheduledEvent "disnake.GuildScheduledEvent").
New in version 2.3.
well this is an event..
events aren't channels
this will create an event which people can join
Guild.edit(public_updates_channel=)
if user.reaction == randomchoiceofbot:
print('')
else:
print('')
nothing can be like this?
Anyone here used cyberduck?
not cyber duck but i use duck in my bath-tub
👍
!resources
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
Guys, I have made a private leaderboards bot for my server which fetch the leaderboards from a url and updates it every 4 seconds (asyncio.sleep) so now I want to make a public version of the bot. but the problem is that I want it to update leaderboards in every server, it is in, every 10 seconds. but if it is in many servers then first it update leaderboards in every server and then sleeps for 10 seconds, but it will slow it down and will then take more than 10 seconds, so is there a way? that it fetch leaderboards every 10 seconds but update in servers within the same 10 seconds e.g.
it fetch leaderboards and then sleeps for 10 seconds before sending another request but while the bot is in sleep mode, it update the other servers and when the 10 seconds complete, it will send another request and then sleeps again
k
First, use tasks
to fetch...ok
Second, just iterate through bot.guilds and get the leaderboard for every guild
but the fetch is ok, but when the bot send message to all guilds, it become a bit slow and then after when I make it sleep for 10 seconds, its been more than 10 seconds(10 seconds sleep + time taken when sending to other guilds)
Could be it's getting ratelimited? In how many guilds is it sending?
tasks.loop will handle that (not the ratelimit, but the time to execute)
I am talking that it will take time in editing leader boards in server
after all edited it will then sleep for 10 secs
then it will edit the leaderboards of 1st server after all this time (10 secs + time taken in other servers)
import disnake
from disnake.ext import commands
import json
import os
client = commands.Bot(command_prefix='-', intents=intents, case_insenstivive = True)
client.warnings = {
guild_id : {}
}
why does it say guild_id not defined?
Cz it isn't defined...?
yes I know that, using asyncio.sleep does that. But tasks.loop doesn't matter on code execution time. It sees if now is last execution time + 10 then execute the code again. While asyncio.sleep wait until the last code is Finished then execute the next code, tasks.loop doesn't
kk
But if you're talking about how to edit/send it simultaniously, you cant
cause ratelimit stuff
for example, you have 1000 guilds, it will take 1000/50 (20 seconds) to edit everything
hello is there a way like in discord.py to see the commands u have and add it to help command …
bc i don’t wanna add all my commands manually i have many commands
!d discord.ext.commands.Bot.commands
property commands: Set[discord.ext.commands.core.Command[discord.ext.commands.core.CogT, Any, Any]]```
A unique set of commands without aliases that are registered.
use this
kk
ok
uhh i didn’t find anything that can help me @visual island
oh get_command?
or idk
@slate swan what do you use for the help command? a normal @bot.command() or MinimalHelpCommand or ?
Whats CogT
Type hinting stuff iirc
how to fetch users reaction?
like fetch_message is there anything like fetch_reaction?
!d discord.Message.reactions @karmic lintel
Reactions to a message. Reactions can be either custom emoji or standard unicode emoji.
!d discord.Reaction is what it returns
class discord.Reaction```
Represents a reaction to a message.
Depending on the way this object was created, some of the attributes can have a value of `None`.
x == y Checks if two reactions are equal. This works by checking if the emoji is the same. So two messages with the same reaction will be considered “equal”.
x != y Checks if two reactions are not equal.
hash(x) Returns the reaction’s hash.
str(x) Returns the string form of the reaction’s emoji.
no messages for more than an hour
You broke inexistent no messages chain
anyone uses mongo db here? is it good if a bot is in one server only?
No
MongoDB is for document data whereas just about everything you do with Discord is relational data
Use the appropriate tools
I personally use postgreSQL for storing data like user ids etc but my client on fiverr wants me to use mongodb
its the client not me.
I don't think it would be hard for them to have an extra 4-5 kb file size with the code
Oh, if your client wants MongoDB, then you could recommend a SQL based db but if they still decline, use Mongo in that case. It still works, in fact, Invite Tracker used it until 6 months ago.
Well , it's okay if you do that
ok. btw is ur fav choice for sql datbase postgres as well?
Absolutely
yep its the best
error
Ignoring exception in command invite:
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "/home/runner/LuminousAquaCopycat/selfroles.py", line 28, in invite
await ctx.send(embed=link, components=components)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord_components/dpy_overrides.py", line 350, in send_override
return await send(channel, *args, **kwargs)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord_components/dpy_overrides.py", line 275, in send
components = _get_components_json(components)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord_components/utils.py", line 27, in _get_components_json
return [row.to_dict() for row in lines] if lines else []
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord_components/utils.py", line 27, in <listcomp>
return [row.to_dict() for row in lines] if lines else []
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord_components/component.py", line 484, in to_dict
"components": [component.to_dict() for component in self.components],
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord_components/component.py", line 484, in <listcomp>
"components": [component.to_dict() for component in self.components],
AttributeError: 'dict' object has no attribute 'to_dict'
whats the issue ??
You already have a dict and you are trying to turn it into dict 
meaning ?
Read it again, it can't get more simple than what he said
i get what he/she is saying....but i dont think that i made a dic...
the same code is working on other bot of mine..
yeah i dont see a dict either, use a fork for buttons then.
it seems like the error comes from where the package location is
You are creating the button the wrong way in the first place, have a look at that code, it's from the developer of discord.py
the exact same code...is working on my other bot...
i just copy pasted it
someone help
this is not working for some reason
@bot.event
async def on_command_error(ctx, error):
if isinstance(error, commands.CommandNotFound ):
await ctx.reply("command not found nig")
@help-python
channel.history doesn't have a check kwarg?
if not, how do I get the messages of a member in a channel to get it into a list?
what do you want to do with the messages? delete them?
ALWAYS print else statements too, you basically have another error but you're hiding it
Get message content
to do what with it?
Put in a file
alright, you basically have to check the first example in the docs, it's doing what you want it to do, but instead of the count, you do your stuff
ah okay
[message.content for message in ctx.channel.history(limt=100) if message.author == member]
i thought there was a check kwarg, though it could be for something else
wrong
don't make it a one liner per se, you're only confusing yourself with it
what's wrong?
in the example on the docs, you'll see that it's an ASYNC loop
[message.content for message in (await ctx.channel.history(limt=100).flatten()) if message.author == member] this?
.
second note: try and see
third note: limit
also, know that a txt isn't a db
a better way of "storing" history of a member can be done via
- directly in on_message
- in every iteration of a message, add it as a db row with the info you like (message_id, member_id, content,...)
It's for a purge command to view the deleted messages a database is unnecessary
then why are you storing it in a txt?
To view them
why don't you just store it as a local variable?
!d discord.on_bulk_messages_deleted
nice
discord.on_bulk_message_delete(messages)```
Called when messages are bulk deleted. If none of the messages deleted are found in the internal message cache, then this event will not be called. If individual messages were not found in the internal message cache, this event will still be called, but the messages not found will not be included in the messages list. Messages might not be in cache if the message is too old or the client is participating in high traffic guilds.
If this occurs increase the [`max_messages`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client "discord.Client") parameter or use the [`on_raw_bulk_message_delete()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_raw_bulk_message_delete "discord.on_raw_bulk_message_delete") event instead.
This requires [`Intents.messages`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.messages "discord.Intents.messages") to be enabled.
There

