#discord-bots
1 messages Β· Page 757 of 1
disnake
very cool
yeah
just move to disnake lol
i will at some point
very easy

This exactly
dang
very poor code
that sucks
pycord gave me a stroke
let me see
the only reason i picked pycord is because it doesn't require any changes from dpy code
disnake is the same
oh really
you just change the word discord to disnake and your done
Internals of dispy is worse
im not sure i havent checked
oh i didn't know that
No documentation found for the requested symbol.
panda really?
π
π
now you do
pycord really
@bot.command()
async def joined(ctx, member: discord.Member):
"""Says when a member joined."""
await ctx.send(f"{member.name} joined in {member.joined_at}")
joined?
lollll
yeah
ok i have a complex here...
my frens keep telling me to use discord.js but i dont wanna learn new lang
so pls tell me python can do all the things which you can do in discord.js
anything you do in djs is possible with python
!traceback
Please provide the full traceback for your exception in order to help us identify your issue.
A full traceback could look like:
Traceback (most recent call last):
File "tiny", line 3, in
do_something()
File "tiny", line 2, in do_something
a = 6 / b
ZeroDivisionError: division by zero
The best way to read your traceback is bottom to top.
β’ Identify the exception raised (in this case ZeroDivisionError)
β’ Make note of the line number (in this case 2), and navigate there in your program.
β’ Try to understand why the error occurred (in this case because b is 0).
To read more about exceptions and errors, please refer to the PyDis Wiki or the official Python tutorial.
yeah
And vice versa
And reversed
Idk what u mean by that lol
did you provide an id inside the get_channel?
Please provide the full traceback for your exception in order to help us identify your issue.
A full traceback could look like:
Traceback (most recent call last):
File "tiny", line 3, in
do_something()
File "tiny", line 2, in do_something
a = 6 / b
ZeroDivisionError: division by zero
The best way to read your traceback is bottom to top.
β’ Identify the exception raised (in this case ZeroDivisionError)
β’ Make note of the line number (in this case 2), and navigate there in your program.
β’ Try to understand why the error occurred (in this case because b is 0).
To read more about exceptions and errors, please refer to the PyDis Wiki or the official Python tutorial.
Yeah, where the lines are
why are you even hiding the id
Idk tbh
you cant do anything with it
well . your error says that you didnt
also , i dont see the channel being defined inside the function
so.... ik most are similar.... just forks of discord.py.... i am fed up now....
pls just tell me one name(library) to start with making bot
ill suggest disnake ( if looking for a fork)
or hikari ( a non-forked library )
im to slow
Ill send in a bit. Taking a shit rn π€£
π§βπ¦―
alright
i can see u have experience in both... soo like which ones comparitively less hassle to setup?
dpy
disnake
both of them are easy , if you aware about discord.py syntax -> go for disnake
if you havent started with anything yet hikari is worth trying , its faster with cache and is well written
tbf we need a whole new library.
comparing both, which one has more features?
Disnake is way more supported since it is a fork of dpy
disnake is more stable and quite easier to get help with since most of people here use it , hikari is a bit hard if you're not too experienced
Any way to make discord bot livestream a clip?
youtube together?
no
k imma go w/ dissnake
π
why?
They can..?
how?
They can?
It's just where he is getting the mp3 from that is the matter.
A radio is a thing lol
Made the clip myself
Idk what you mean by stream you can just use playback.
It's certainly not easy though
i believe i can watch discord.py yt tutorials for starting in disnake?
I can think of a lot of reasons why this would never ever happen
just the same you just have to change the word discord to disnake
watch discord.py tutorials again
oh right right lol
!d discord
In order 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.
and the examples folder in github repo
!resources here u go
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
thx
is it not possible to make a self bot anymore?
dpy tutorial: https://vcokltfre.dev/
how to migrate to disnake: https://guide.disnake.dev/
disnake examples: https://github.com/DisnakeDev/disnake/tree/master/examples
it is but its againts tos
No + we don't condone them.
is against rule 5
ya
thx
time to sleep
count them yourself ez
πββοΈ this is the time i wake up at lol
π©
just go to some bot's panel
and log in
it shows how many servers u r in
!resources
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
For all problems use this dude @unkempt canyon
it can work as a interpreter ( !e command ) , or lookup for the library docs . not actually talk lol
oo
@slate swan
import os
import sys
import asyncio
import discord
import random
import json
import os
from discord.ext import tasks
from discord import File, Message
from discord.ext import commands
from discord.ext.commands import Bot
from discord.ext import tasks
from discord import Webhook, RequestsWebhookAdapter
bot = commands.Bot(command_prefix="s")
bot.remove_command("help")
h = bot.get_channel(706675003952857109)
@bot.event
async def on_connect():
print (f'bot \nLogged in as: {bot.user}')
@tasks.loop(seconds = 62)
async def myloop():
await h.send("Remember guys! No profanity :)")
myloop.start()
bot.run("jojojojoj")
h will always be None
?
since your bot is not running and you defined that variable
???
Lemme see the error i get when i move it into the area
any error or something
can u put the correct codes to make a bot
@bot.event
async def on_connect():
print (f'Advertise bot \nLogged in as: {bot.user}')
h = bot.get_channel(706675003952857109)
@tasks.loop(seconds = 62)
async def myloop():
await h.send("Remember guys! No profanity :)")
myloop.start()
tysm
inside the function....
put it inside your task loop
oh im sorry, its been like a year since ive coded lol
@bot.event
async def on_connect():
print (f'Advertise bot \nLogged in as: {bot.user}')
@tasks.loop(seconds = 62)
async def myloop():
h = bot.get_channel(706675003952857109)
await h.send("Remember guys! No profanity :)")
@slate swan can u put the correct code then
you can start with defining a bot variable which would be a discord.ext.commands.Bot variable , and running it using bot.run()
tysm
k
?
this guy is confusing me
why is he thanking me
ya, thank u so much
they probably thought your code was directed to them
so this one is the correct ?
File "C:\Users\Danny\Desktop\VSProjects\securitybot\main.py", line 28, in myloop
await h.send("Remember guys! No profanity :)")
AttributeError: 'NoneType' object has no attribute 'send
```@slate swan
the id is wrong , please recheck it
which one is correct
706675003952857109
i just right clicked on the channel and pasted after clicking copy id
#706675003952857109 @slate swan see the channel mentioned?
put await bot.wait_until_ready() in the tasks.loop
?
@tasks.loop(seconds = 62)
async def myloop():
h = bot.get_channel(706675003952857109)
await bot.wait_until_ready()
await h.send("Remember guys! No profanity :)")
``` @visual island
right there?
before get_channel
ohh
if you see it as #deleted-channel , the id is invalid 
@tasks.loop(seconds = 62)
async def myloop():
await bot.wait_until_ready()
h = bot.get_channel(706675003952857109)
await h.send("Remember guys! No profanity :)")
so- do i do #<706675003952857109>
recheck the id of the channel pls
and yes , do what icy said
i did
@slate swan```py
@tasks.loop(seconds = 62)
async def myloop():
await bot.wait_until_ready()
h = bot.get_channel(706675003952857109)
await h.send("Remember guys! No profanity :)")
right here, right?
yea , should work
File "C:\Python310\lib\asyncio\base_events.py", line 510, in _check_closed
raise RuntimeError('Event loop is closed')
RuntimeError: Event loop is closed
```@slate swan
you forgot to await something
do i need to await my bot.run?
discord.errors.LoginFailure: Improper token has been passed.
is in there
the error says pretty much itself
Improper token has been passed.
@slate swan this is handy
TYPE STRUCTURE EXAMPLE
User <@USER_ID> @split rivet
User (Nickname) <@!USER_ID> @split rivet
Channel <#CHANNEL_ID> [#103735883630395392](/guild/267624335836053506/channel/103735883630395392/)
Role <@&ROLE_ID> <@&165511591545143296>
Standard Emoji Unicode Characters π―
Custom Emoji <:NAME:ID> :mmLol:
Custom Emoji (Animated) <a:NAME:ID> :b1nzy:
Unix Timestamp <t:TIMESTAMP> <t:1618953630>
Unix Timestamp (Styled) <t:TIMESTAMP:STYLE> <t:1618953630:d>
ok, so there is no way to count the servers that I am in other than manually doing it?
What do you mean?
Returns a list of the guilds the bot is in
I am talking about my own account, which would be a selfbot
hes using a selfbot
they are doing that for their user account
is sure did, thank you
late night programing by yourself is the best
My commands_ran command actually kicked my ass
π
ctrl+c , ctrl+v from stackoverflow is best
!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.
but then its from 2004π
It works doe
seems good to me , except for the use of f strings
sql injection but your fine
f strings in sql queries is bad
hes not getting user input
Why?
yea its fine there , just saying
Yeah ik about that
plus you can inject anything with f string
I'm not getting any user input
But lets say I wanted to store a welcome channel, how would I do it?
INSERT INTO table_name (column1, column2, column3, ...)
VALUES (value1, value2, value3, ...);
ez
execute("insert into table atrr VALUES ( ?)" , (value_to_insert,))
So how is this better than an f stirng?
use f strings still
but just in that format
I do use the format you sent
its the same thing?
wdym?
its the same thing
async def add_commands_ran(self, ctx: commands.Context) -> bool:
cursor = await self.connection.cursor()
await cursor.execute(f"SELECT commands_ran FROM commands_ran WHERE user_id={ctx.author.id} and guild_id={ctx.guild.id}")
is_none = await cursor.fetchone()
if is_none is None:
await cursor.execute(f"""INSERT INTO commands_ran(user_id, guild_id, commands_ran)
Values({ctx.author.id}, {ctx.guild.id}, 1)""")
await self.connection.commit()
return True
else:
await cursor.execute(f"""DELETE FROM commands_ran WHERE user_id={ctx.author.id} and guild_id={ctx.guild.id}""")
await cursor.execute(f"""REPLACE INTO commands_ran(user_id, guild_id, commands_ran)
Values({ctx.author.id}, {ctx.guild.id}, {is_none[0] + 1})""")
await self.connection.commit()
return True
This is what I use to add the commands that were ran
I shouldn't be worried about sql injection in this case, correct?
So if I was doing something like, storing a help channel, I would want to use this correct?
Hey, who wants to have a fun conversation with me in the voice chat? I will share the topic with you when you join
The variable name though lol
always use it
its good practice
I'm going to get bullied when I publish my bot on github

Is it worth to manually go through all my current code and change it?
if it doesnt take user input no but just use it from now on
since you're not taking any string input from the user , it doesnt really matter in your case
Oh wait, I have a custom prefix command which takes user input. Would I have to change it to prevent injection?
and here's the reason why the placeholder prevents the injection ```
Between Cache and Execution, there is an additional step: Placeholder Replacement. At this point, the placeholders are replaced with the userβs data. However, the query is already pre-compiled (Binding), so the final query will not go through compilation phase again. For this reason, the user-provided data will always be interpreted as a simple string and cannot modify the original queryβs logic. Thus, the query will be immune to SQL Injection vulnerabilities for that data.
sql injection happens i.e you wait for a name and he inserts sql statements and you will blindly execute the statement which can be used for bad stuff
it's not the query but just a value if you use placeholders
So is this bad?
https://paste.pythondiscord.com/efolipukew.rust
if is_none is None lol usually I name that variable data
if youre using place holders your fine
What are those?
?
for example if i had py f"INSERT INTO prefixes ( id , prefix ) VALUES ( {id} , {prefix}" i'd change it to py f"INSERT INTO prefixes ( id , prefix ) VALUES ( ? , ?)", (id , prefix )
nothing too complicated
why still f strings though
Would I add quotes around prefix since its meant to be text?
sorry i just copy paste the above part
doesnt matter
This is the table structure
ill assume its a variable since if its a constant no point of using f string exist
I meant like this:
INSERT INTO prefixes ( id , prefix ) VALUES ( ? , '?'), (id , prefix )
is this aiosqlite?
you can do that too , but it doesnt matter
quotes
yes
sqlite3 + aiosqlite same
So it automatically gets converted to text?
yessir
Good
just the async bridge
When I don't use quotes sqlite3 yells at me (if its meant to be text)
its just like doing str(prefix)
it doesnt execute it as a statement but as a str
well raw sql would do that but not a python sql query
await cursor.execute(f"""REPLACE INTO prefixes(guild_id, prefix)
Values({ctx.guild.id}, '{prefix}')""")
If I removed the quotes around {prefix} I get a lot of angry errors
So do I just not have to worry about that if I'm using the question marks?
how can i make it so i can check a date and how much time has passed since that date
nope . it works like a charm with/without the quotes
Thanks
use the datetime object and subtract it from current datetime
So I'll change this command and start using the question marks instead
can i store a datetime obj in a db?
Why not use a timestamp?
Whaaaat?
Thats what I do to check my uptime
its for a sober command β€οΈ
probably
I meant the .timestamp() (method or whatever its called) from the datetime lib
ahhhhh mhmmm
Store the timestamp and subtract from the current time
Works like a charm for my uptime command
Shit I lost the code
πββοΈ i save the first datetime for the boot as a bot property and subtract it from current datetime to get the uptime
UPDATE prefixes SET prefix=? WHERE guild_id=?
anyone knows where self.persistent_views_added = True is needed for making persistent dropdown?
Literally what I do but I use a timestamp
Nvm, something is still wrong
Since discord auto converts
wrong indentation
I can just pass the timestamp into <t:timestamp>
aghhh
And I'm chilling
Thank you
yeah an unix timestamp is a great thing to use :p
i put it in a yaml codeblock so i need it to be a timedelta
@slate swan still my bot is not responding
show code
wat to d
I just send it in a normal embed description
ctx.message.created_at
okay
maybe print what timezone
looks good but you should show how much time has passed
bot.event
async def on_connect():
print (f'Advertise bot \nLogged in as: {bot.user}')
@tasks.loop(seconds = 62)
async def myloop():
h = bot.get_channel(706675003952857109)
So use a different converter or add another line?
other code>
wait
make a new line that says
time online: 3h 1day
i just mention the uptime in my botinfo cmd
or something else
do u even run the bot?
So <R:timestamp>
@slate swan would you happen to know
The commands work but when I do the second command help g. The first command executes with it
wut
lemme read the docs , gimme a moment
ive been using hikari even before discord.py was discontinued
@heavy radish checkup invoke decoration for group commands
Am I doing anything wrong: <R:{round(self.bot.start_up_time)}>
?
Its not showing as a timestamp
Ahh, Thank you
what's bot.start_up_time
Unix timestamp. Doesn't matter. Its working for my previous timestamp
This is the result I'm getting
it must be like <t:timestampinteger:R>
<t:164247925:R>
Oh alr. My first timestamp was like <t:{round(self.bot.start_up_time)}>
And it was working
yeah but rn you have <R:timestamp>
I know
I was confused whether to put it at the end or the beginning
Oh I didn't have to put it because it defaulted to what I wanted
Looking fresh
can someone send me all the time formats like unix delta and others
put it in the end
thx
.bm
@slate swan can u give url for page?
what library is that?
I have no clue how to get a direct link
Integrate your service with Discord β whether it's a bot or a game or whatever your wildest imagination can come up with.
But its here. You can search for Timestamp Styles and it will show up
disnake
Integrate your service with Discord β whether it's a bot or a game or whatever your wildest imagination can come up with.
!resources
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
Integrate your service with Discord β whether it's a bot or a game or whatever your wildest imagination can come up with.
that one is exact
thats the very first thing which appears in the url i sent too :p
@slate swan thanks does them format work in d.py/disnake or ?
and what's self here ? a view class?
yeah but i have to scroll down which is a painπΆ
it words on any kind of discord message
It's discord
ah sweet
including about mes
anyone knows a bot that can send a message on a specific time
will be in handy showing how longa stream been running
how?
broken code:```py
@bot.event
async def on_command_completion(ctx):error:py
async def on_command_completion(ctx):
^
SyntaxError: invalid syntax```
i dont get whats wrong
something above is making it give an error
use tasks loop and check current datetime
bot.event?
before that i only have the status setter on ready
show that part
show error msg
async def on_command_completion(ctx):
^
SyntaxError: invalid syntax
# Setup the game status task of the bot
@tasks.loop(minutes=1.0)
async def status_task():
await bot.change_presence(activity=nextcord.Game(config["status"])
thats the status part
is it smthing like sublime
ah , its just a custom attribute defined there
thats not really a property of a view
oh...i see
if a view has timeout = None , and all the items in the view has a custom id , it will be persistent
is there no get_message function?
i want to get a message then message.edit new stuff
why no get?
!d discord.TextChannel.fetch_message
await fetch_message(id, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Retrieves a single [`Message`](https://discordpy.readthedocs.io/en/master/api.html#discord.Message "discord.Message") from the destination.
O yeah it's in TextChannel
messages would be too heavy to cache
yeah thats true
what is /
everything before it is a positional argument
you can ignore that py message = await channel.fetch_message(id) will do the job
^^^
oh wait i need to get the channel first?
message is probably not sent when discord sends GUILD_CREATE? Idk
yea , since fetch_message is something limited to channels
prob not what sarthak said does make sense tho
You can't cache it if it's not sent on establishing a connection tho
getting a channel is just await bot.get_channel(id) right
You can but eh, why would you
ok
It's not a coroutine
it's a subroutine!
ah wut
aka a normal function
no
you dont await it

Caching messages would be a mess for your memory, especially when you look at how much RAM caching only members takes ^^
i went to discord.py looking for actual reason for get_message not existing lol
yeah thats true
though if you have a guild object already, it's better to use guild.get_channel(channel ID)
π

it's existent but cannot be used , for the cache thing we talked earlier
i didnt get u
!d discord.ext.tasks.loop use this to loop a function multiple time
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").
!d datetime.datetime.now use this to check current time
classmethod datetime.now(tz=None)```
Return the current local date and time.
If optional argument *tz* is `None` or not specified, this is like [`today()`](https://docs.python.org/3/library/datetime.html#datetime.datetime.today "datetime.datetime.today"), but, if possible, supplies more precision than can be gotten from going through a [`time.time()`](https://docs.python.org/3/library/time.html#time.time "time.time") timestamp (for example, this may be possible on platforms supplying the C `gettimeofday()` function).
If *tz* is not `None`, it must be an instance of a [`tzinfo`](https://docs.python.org/3/library/datetime.html#datetime.tzinfo "datetime.tzinfo") subclass, and the current date and time are converted to *tz*βs time zone.
This function is preferred over [`today()`](https://docs.python.org/3/library/datetime.html#datetime.datetime.today "datetime.datetime.today") and [`utcnow()`](https://docs.python.org/3/library/datetime.html#datetime.datetime.utcnow "datetime.datetime.utcnow").
if the time is same as the time you want , do your stuff , else dont
can u do an example π
from datetime import datetime
from discord.ext import tasks
@tasks.loop(hours = 24) # do it everyday
async def my_task():
if datetime.now() == your_datetime:
# do stuff
this keeps running every 24 hrs
There are multiple examples here
https://discordpy.readthedocs.io/en/stable/ext/tasks/index.html
hey
Traceback (most recent call last):
File "F:\backup\Fate\init.py", line 12, in <module>
bot.load_extension('cogs.Inventory')
File "C:\Users\rajes\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\bot.py", line 678, in load_extension
self._load_from_module_spec(spec, name)
File "C:\Users\rajes\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\bot.py", line 609, in _load_from_module_spec
raise errors.ExtensionFailed(key, e) from e
discord.ext.commands.errors.ExtensionFailed: Extension 'cogs.Inventory' raised an error: AttributeError: module 'discord.ext.flags' has no attribute 'add_flag'
why i m getting this error
even though add_flag is an attribute
what library is that?
There is this
!d discord.ext.commands.Flag
class discord.ext.commands.Flag```
Represents a flag parameter for [`FlagConverter`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.FlagConverter "discord.ext.commands.FlagConverter").
The [`flag()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.flag "discord.ext.commands.flag") function helps create these flag objects, but it is not necessary to do so. These cannot be constructed manually.
yea but they import it from ext
It's not in ext.flags
a command object has that attribute right?
It's in ext
And there is no add_flag method existing at all.
there was
maybe updated
async def run_once(self):
await self.bot.wait_until_ready()
self.add_view(DropdownView())
So...I have this function in a cog. I want to import it to the main file and do
loop = asyncio.get_event_loop()
loop.create_task(run_once())```
I'm a bit confused on where to put `self`
i dont know whats new
why dont u do that in the cog itself?
you can do it inside the __init__ or setup() function
you mean make the loop there?
It worked yesterday
There never was.
so maybe different flag library
await set_permissions(target, *, overwrite=see - below, reason=None, **permissions)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Sets the channel specific permission overwrites for a target in the channel.
The `target` parameter should either be 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") that belongs to guild.
The `overwrite` parameter, if given, must either be `None` or [`PermissionOverwrite`](https://discordpy.readthedocs.io/en/master/api.html#discord.PermissionOverwrite "discord.PermissionOverwrite"). For convenience, you can pass in keyword arguments denoting [`Permissions`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions "discord.Permissions") attributes. If this is done, then you cannot mix the keyword arguments with the `overwrite` parameter.
If the `overwrite` parameter is `None`, then the permission overwrites are deleted.
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...
set_permissions
ok
What permission is my BOT missing?
Well, the library got deleted.
why tf
@slate swan sorry for ping but icymi
I am not the developer of that library, ask the developer why they removed the library ;)
i mean , you can call that function inside the cog too , why import it in the main file and call it?
f
where would I run it?
Anyone?
calling the function? just use the init of the cog , or the setup function , it gets called as soon as the cog is loaded
probably cant edit a channel
uhmm could you give an example please excuse my lack of knowledge with functions
self is a cog there right?
yeah
Which perm is that? I think I've enabled them all
Does the position of the BOT matter?
Manage channels
It's enabled
class TheCog(Cog):
def __init__(.... -> None:
loop = asyncio.get_event_loop()
loop.create_task(self.run_once())
async def run_once(self):
await self.bot.wait_until_ready()
self.add_view(DropdownView())
If it edits the permission for higher role I guess so
@spring flax
It edits permission of everyone role
Does the channel have any other overwrites
It might also be manage roles
Alr gave it
yes
If it has any overwrites for roles that the bot has and those overwrites are manage channel = false then you need to remove those or add additional overwrites for the bot set to true
Imma check docs maybe it tells what permission exactly you need
!d discord.TextChannel.set_permissions
await set_permissions(target, *, overwrite=see - below, reason=None, **permissions)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Sets the channel specific permission overwrites for a target in the channel.
The `target` parameter should either be 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") that belongs to guild.
The `overwrite` parameter, if given, must either be `None` or [`PermissionOverwrite`](https://discordpy.readthedocs.io/en/master/api.html#discord.PermissionOverwrite "discord.PermissionOverwrite"). For convenience, you can pass in keyword arguments denoting [`Permissions`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions "discord.Permissions") attributes. If this is done, then you cannot mix the keyword arguments with the `overwrite` parameter.
If the `overwrite` parameter is `None`, then the permission overwrites are deleted.
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...
Yeah it's manage roles
None of the other roles have manage role except staff role
which I can't remove
Try adding overwrite for bot role to manage channel to true
Done
Doesn't work. I've tried other server and it works
Does the bot even have the permission to see the channel
yes
Seems like the issue is in role permissions and/or overwrites
What else can I do? Will Admin perms do it
Not recommended to give admin perms to bots but it will work for sure
@heavy radish you don't mind inviting me to the server so I can see myself?
It's not mine
Oh
It's a public server and i can't give power
it says DiscordSupport object has no attrbiute add_view
class DiscordSupport(commands.Cog):
def __init__(self, bot):
self.bot = bot
loop = asyncio.get_event_loop()
loop.create_task(self.run_once())
async def run_once(self):
await self.bot.wait_until_ready()
self.add_view(DropdownView())
@heavy radish try printing the manage_channel permission for the bot in the channel
It's like
!d discord.TextChannel.permissions_for
permissions_for(obj, /)```
Handles permission resolution for the [`Member`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member "discord.Member") or [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role").
This function takes into consideration the following cases...
And Member has a similar method they work the same iirc
because self is a cog object , and it does not have that method
thats the reason why i asked about it here
yeah I realized but not sure what to do lol
whaty r u trying to do?
print(before)
print(after)
Nothing happens.. I have intent enabled as well.
bot = commands.Bot(command_prefix='!', intents=intents)
add the persistence view when the bot is ready
you did @bot.event on top right?
π ty
What is different between
discord.on_member_update(before, after)
discord.on_user_update(before, after)
!d discord.on_user_update
discord.on_user_update(before, after)```
Called when a [`User`](https://discordpy.readthedocs.io/en/master/api.html#discord.User "discord.User") updates their profile.
This is called when one or more of the following things change:
β’ avatar
β’ username
β’ discriminator...
nothing
user is a user obj and member is a member obj
!d discord.on_member_update
discord.on_member_update(before, after)```
Called when a [`Member`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member "discord.Member") updates their profile.
This is called when one or more of the following things change:
β’ nickname
β’ roles
β’ pending...
what do you mean nothing
their aliases
No?
Member is subclass of User
^
Member provides more guild specific functionality
why not?
if you leak your token your bot can do anything so thats why its recommended to only add the perms you need
not recommended still
my bot is owner
wut
Lol
of guild
did you gaved your bot owner?
cant do that
!d discord.ext.commands.Bot.create_guild
await create_guild(*, name, region=<VoiceRegion.us_west: 'us-west'>, icon=..., code=...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Creates a [`Guild`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild "discord.Guild").
Bot accounts in more than 10 guilds are not allowed to create guilds.
this?
but create server from bot n invite urself
apperently u cant make slash commands wen bot is owner
n i used template wen setup guild for easier start
Isn't this how I make a request?
import requests
import os
url = "https://discordapp.com/api/users/889705507286310972"
payload = {}
headers = {"Authorization": "{{" + os.getenv("BOT_TOKEN") + "}}"}
response = requests.request("GET", url, headers=headers, data=payload)
print(response.text)
BOT_TOKEN is my discord bot token.
No getting any errors but all I get is an {"message": "401: Unauthorized", "code": 0} printed on the screen. What am I doing wrong here?
how do you get nickname update on discord.on_user_update
i did after.name, but didnt work
There is no on_user_update event.
@slate swan
ok come to #sir-lancebot-playground
There is no {{ and }} needed.
I did
import requests
import os
url = "https://discordapp.com/api/users/889705507286310972"
payload = {}
headers = {"Authorization": "{{" + os.getenv("BOT_TOKEN") + "}}"}
response = requests.request("GET", url, data=headers)
print(response.text)
And I got
[some more stuff was printed on the screen]
<p>Your client has issued a malformed or illegal request. <ins>Thatβs all we know.</ins>
Am I sending too many requests or something? Should I be concerned ?
Can you stop?
I meant it's not the event you're looking for.
You're looking for the on_member_update event.
Which gives Member objects back which contains the nickname attribute.
Well i mean, im using on_member_update and it doesnt return nickname change
bot = commands.Bot(command_prefix='!', intents=intents)
@bot.event
async def on_member_update(before, after):
# print(before)
print(after.nickname)```
As I said, the authorization Header needs to be like that
Authorization: Bot <Token>
And not
Authorization: {{<Token>}}
Which is what you have
BTW would be better to use internals lol
It's .nick, not .nickname.
@bot.command(pass_context = True)
@commands.has_permissions(manage_roles=True)
async def mute(ctx, member: discord.Member,*, reason=None):
if member == ctx.author:
em1=discord.Embed(description=f"**you** cannot `mute` yourself", colour=discord.Colour.red())
await ctx.send(embed=em1)
else:
guild = ctx.guild
mutedRole = discord.utils.get(guild.roles, name="muted loser")
x = get_role(925322561775099934)
x1 = get_role(925320902692974613)
x2 = get_role(918684634341072929)
x3 = get_role(919183869264146522)
x4 = get_role(919191088365994004)
x5 = get_role(923187785303728148)
x6 = get_role(924258916106403871)
await member.remove_roles(x, x1, x2, x3, x4, x5, x6)
em2=discord.Embed(description=f"{member.mention} has been `muted` for **{reason}**", color=discord.Colour.green())
em3=discord.Embed(description=f"{member.mention}, you have been `muted` for **{reason}**", colour=0)
await ctx.send(embed=em2)
await member.send(embed=em3)
await ctx.add_roles(member, mutedRole)```
the x variables come up as errors but it doesnt say which error it is
I would use as URL
https://discord.com/api/v9/...
guys how can i display when my bot connects to a website with aiohttp?
display?
sorry like how can i check when my bot connects to a website with aiohttp
Make a task which should make a POST request to the server?
What type of communication technique the server use? Raw tcp/ip, websockets or http sessions? If latter then yeah create a task which should run and make POST req when the bot is ready
when I do channel = await guild.create_channel(...) how do I set the channel topic to the ID of what was just created?
let me check
wdym
just uses http request
like if I make the channel and it's Id is 1234, how do I set that in the channel topic
Yeah then do what I said
a POST request is like a get right
uhh is it for any event which happened or just channel?
btw i ment get like gurd
Well, uh not really it's a different method, it sends the object to server but yeah
channel_to_send = await guild.create_text_channel(name="ModMail channel", category=category, topic=f"ModMail Channel {member.id}" ) If I wanted to add the channel_to_send's ID in the topic of the channel
ic i thought it was the same so its just different protocols ?
The protocol is same, hyper text transfer protocol, the method is diff!
ahhh ic
so just make a POST request and when i do just print that its ready?
well you sent the payload to the server, now do whatever you like
what if i dont want to do nothing just do something useless orrrr
What you talking about lol, you asked me to tell how to make a server aware that your bot is connected to discord, so after you make the request do whatever you wanna do lol it doesn't matter
ok got it thank you nova
Hello!!
Hope you all are doing well.
Im working in a discord bot, but i need some help in get the list of users from servers.
If anyone wants to help me I will be really thankful!
Great night/day to everyone
!d discord.Guild.members
property members: List[discord.member.Member]```
A list of members that belong to this guild.
Use that
Hey thanks!
@idle saffron it needs members intent BTW
edit channel set topic to channel.id
Actually u will have to do another API call
Since u won't have the ID before making the channel
channel = await create(...
await channel.edit(topic=channel.id)
``` kinda
Yea this is what u'll have to do
Shebang
???
why do you wanna edit the channel topic to the channel id? weird request
Their name is a shebang!
whose
^
Ah
Indeed im making a discord mass dm bot, someone can help me pls?
No
Against ToS
lol
I just need help with few things
monka
Still
@idle saffron turn on roblox instead
why
is that necessary ?
morning
havnt slept for two days :/
Sleep tight
thx
How do i send msg whichsends the perms required by the bot when a cmd is executed but the bot doesnt have the permission
Use error handlers
I do but it doesnt work, i guess its done by putting the code in every single command
you need to use @commands.bot_has_permissions decorator for that
else the error wont be raised
how would i make something like this but sort it out with roles
and if the roles r the same
use alphabetical order
and create an exeption for roles like staff and owner
would that be hard
no answer = guessing its hard
!e py a = ['z' , 'a','s'] print(sorted(a))
@slate swan :white_check_mark: Your eval job has completed with return code 0.
['a', 's', 'z']
how would i sort out
what is top roles
with exception of staff and owner
im kinda making like a ranking system
remove the staff and owner role from the list before sorting
you have a list of role names or role objects?
i dont have a list of role names wdym a list of role names
do i have to create one
i dont understand what u mean
!d discord.Guild.roles
property roles: List[discord.role.Role]```
Returns a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.9)") of the guildβs roles in hierarchy order.
The first element of this list will be the lowest role in the hierarchy.
@green bluff it's already sorted
The first element of this list will be the lowest role in the hierarchy.
so do i only list the roles up till the role which is not staff?
like pretend its a userinfo command
if a person has staff or owner i dont want that to be listed as their top role
i want to create an exception like dont list those roles
if a person has those
as their top role
!d discord.Member.top_role
property top_role: Role```
Returns the memberβs highest role.
This is useful for figuring where a member stands in the role hierarchy chain.
ik
so u know when i do top_role
it says im owner right
but i dont want it to list that im owner or staff
i want it to list the top role thats below staff
Ah
I guess access member.roles and remove the roles from the list till staff role
Using slicing
!e
print([1, 62, 92, 74][:2])
@maiden fable :white_check_mark: Your eval job has completed with return code 0.
[1, 62]
class slice(stop)``````py
class slice(start, stop[, step])```
Return a [slice](https://docs.python.org/3/glossary.html#term-slice) object representing the set of indices specified by `range(start, stop, step)`. The *start* and *step* arguments default to `None`. Slice objects have read-only data attributes `start`, `stop`, and `step` which merely return the argument values (or their default). They have no other explicit functionality; however, they are used by NumPy and other third-party packages. Slice objects are also generated when extended indexing syntax is used. For example: `a[start:stop:step]` or `a[start:stop, i]`. See [`itertools.islice()`](https://docs.python.org/3/library/itertools.html#itertools.islice "itertools.islice") for an alternate version that returns an iterator.
How does one get the message history and put it in a text file?
ohh so :2 removes the last 2 highest numbers
!d discord.TextChannel.history
async for ... in history(*, limit=100, before=None, after=None, around=None, oldest_first=None)```
Returns an [`AsyncIterator`](https://discordpy.readthedocs.io/en/master/api.html#discord.AsyncIterator "discord.AsyncIterator") that enables receiving the destinationβs message history.
You must have [`read_message_history`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.read_message_history "discord.Permissions.read_message_history") permissions to use this.
Examples
Usage...
and i do that with roles
I know the channel.history(**kwargs) but what about the txt file
No, it runs the loop till the 2nd element (doesn't include the 3rd element)
See the docs, it has a way to convert the messages to a list
!d discord.AsyncIterator.flatten
await flatten()```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Flattens the async iterator into a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.9)") with all the elements.
oh .flatten() right
Yes, or till the element with index 4
Yea
index 4?
okay when I have the list how do I put it in a txt file lol
oh so it goes from 0 to 4
Yooo wait, u need to put the message objects???
Or the message content
how would i do that with roles tho
the message author, the time and the content
like role = ctx.guild.roles
Just use list comprehension
!d open exists
open(file, mode='r', buffering=- 1, encoding=None, errors=None, newline=None, closefd=True, opener=None)```
Open *file* and return a corresponding [file object](https://docs.python.org/3/glossary.html#term-file-object). If the file cannot be opened, an [`OSError`](https://docs.python.org/3/library/exceptions.html#OSError "OSError") is raised. See [Reading and Writing Files](https://docs.python.org/3/tutorial/inputoutput.html#tut-files) for more examples of how to use this function.
*file* is a [path-like object](https://docs.python.org/3/glossary.html#term-path-like-object) giving the pathname (absolute or relative to the current working directory) of the file to be opened or an integer file descriptor of the file to be wrapped. (If a file descriptor is given, it is closed when the returned I/O object is closed unless *closefd* is set to `False`.)
list = [msg-1, msg-2]
final = [(msg.content, msg.created_at, msg.author.name) for msg in list]
Idk something like this should work
There was an easier way with itertools iirc
for me or for dia
Dia
do you know what this is? or docs?
U gotta find out yourself
Lemme see if I can find it
allg thanks
!d itertools.groupby
@spring flax I haven't really tried, but try
No documentation found for the requested symbol.
itertools.groupby(iterable, key=None)```
Make an iterator that returns consecutive keys and groups from the *iterable*. The *key* is a function computing a key value for each element. If not specified or is `None`, *key* defaults to an identity function and returns the element unchanged. Generally, the iterable needs to already be sorted on the same key function.
The operation of [`groupby()`](https://docs.python.org/3/library/itertools.html#itertools.groupby "itertools.groupby") is similar to the `uniq` filter in Unix. It generates a break or new group every time the value of the key function changes (which is why it is usually necessary to have sorted the data using the same key function). That behavior differs from SQLβs GROUP BY which aggregates common elements regardless of their input order.
!e
print("You sussy baka")
@slim plover :white_check_mark: Your eval job has completed with return code 0.
You sussy baka
#bot-commands
Hey @ember magnet!
It looks like you tried to attach a Python file - please use a code-pasting service such as https://paste.pythondiscord.com
!d zip or try using this, I don't really know
zip(*iterables, strict=False)```
Iterate over several iterables in parallel, producing tuples with an item from each one.
Example:
```py
>>> for item in zip([1, 2, 3], ['sugar', 'spice', 'everything nice']):
... print(item)
...
(1, 'sugar')
(2, 'spice')
(3, 'everything nice')
```...
my discord bot is an absolute mess, I have all the commands not as cogs just as
@bot.command() async def help(ctx):
etc...
would organising it into cogs just be as simple as
putting it inside a class that inherits from cogs and creating the command in there?
fuck it, ill work it out, it's a hard question to answer not knowing what i know dw haha
https://paste.pythondiscord.com/ahozokahow.py
Line 122
I tried to make a Ticket System but the bot wont react on the on_reaction_add event. It worked fine when I tested it first, but then i wanted to enhance it more and now it just doesnt react anymore. I tried to undo my changes and test it with print, but nothing works and i dont get any error message. I cant see what im doing wrong
if channelexsits:
None
What is this?
import discord
from discord import Client, Intents, Embed
from discord_slash import SlashCommand, SlashContext
from discord.ext import commands
@commands.has_permissions(ban_members=True)
@client.command(pass_context=True)
async def BanUser(ctx, user: discord.Member=None, *, reason="The reason was not entered"):
if user is None:
await ctx.send("Please enter the user you want to ban.")
elif user == ctx.message.author:
await ctx.send("You cannot ban yourself.")
elif user.guild_permissions.administrator:
await ctx.send("You cannot ban a admin.")
else:
await user.ban(reason=reason)
await ctx.send(f"Banned {user.name} for {reason} by {ctx.author.mention}")
how to turn it into a slash command?
btw you reloaded your bot before trying again after the change right?
using two different modules for the bot and slash commands can be complicated, i suggest you to use disnake
F
yeah
!d on_raw_reaction_add
on_reaction_add works for message which are stored in the cache, once your bot turns offline it deletes the cache, you should use on_raw_reaction_add
i'm stupid today
D_D
why complicated?
!d disnake.on_raw_reaction_add
disnake.on_raw_reaction_add(payload)```
Called when a message has a reaction added. Unlike [`on_reaction_add()`](https://docs.disnake.dev/en/latest/api.html#disnake.on_reaction_add "disnake.on_reaction_add"), this is called regardless of the state of the internal message cache.
This requires [`Intents.reactions`](https://docs.disnake.dev/en/latest/api.html#disnake.Intents.reactions "disnake.Intents.reactions") to be enabled.
Because they are two different modules, disnake is one single module and has them both, is more simple
how to use it
whats the different having tro different modules
Doesnt knew that thank you very much know He reacts
well but anyways
@commands.has_permissions(ban_members=True)
@slash.slash(name="Ban", description="Bans a user")
async def BanUser(ctx, user: discord.Member=None, *, reason="The reason was not entered"):
if user is None:
await ctx.send("Please enter the user you want to ban.")
elif user == ctx.message.author:
await ctx.send("You cannot ban yourself.")
elif user.guild_permissions.administrator:
await ctx.send("You cannot ban a admin.")
else:
await user.ban(reason=reason)
await ctx.send(f"Banned {user.name} for {reason} by {ctx.author.mention}")
why doesnt this create a slash command
it is a fork of discord, so you will have to change nothing in your code except that you have to change every discord into disnake, there is an example of a slash command:
from disnake.ext.commands import *
from disnake import ApplicationCommandInteraction
# your client / bot here
...
@slash_command(name="echo", description="Send a message")
async def echo(ctx: ApplicationCommandInteraction, message: str):
await ctx.send(message)
the message is an option of the slash command so it will appear when you will digit /echo
there is a classic command with disnake:
from disnake.ext.commands import *
...
@bot.commands()
async def echo(ctx: Context, message: str):
await ctx.send(message)
no problem
how to make this work with disnake? @placid skiff
i get error while trying to do slash_command
i don't know how discord_slash works so i can't help you with that. I repeat to you, disnake is better, is the same as discord but with slash commands
ok
subclass commands.HelpCommand
!d discord.ext.commands.HelpCommand
class discord.ext.commands.HelpCommand(*args, **kwargs)```
The base implementation for help command formatting.
Note
Internally instances of this class are deep copied every time the command itself is invoked to prevent a race condition mentioned in [GH-2123](https://github.com/Rapptz/discord.py/issues/2123).
This means that relying on the state of this class to be the same between command invocations would not work as expected.
HelpCommand walkthrough https://gist.github.com/InterStella0/b78488fb28cadf279dfd3164b9f0cf96
code:
@bot.command()
@commands.has_permissions(kick_members=True)
async def warn(ctx, member: discord.Member, *, reason):
save_warn(ctx, member)
dm = await bot.fetch_user(member.id)
em=discord.Embed(title="Warning", description=f"Server: {ctx.guild.id}\nReason: {reason}"
await dm.send(embed=em)
@bot.command()
@commands.has_permissions(kick_members=True)
async def warnings(ctx, member: discord.Member):
warns = warns_check(member)
await ctx.send(f"{member.name} has {warns} warnings.")
@bot.command()
@commands.has_permissions(kick_members=True)
async def removewarn(ctx, member: discord.Member, amount: int):
remove_warn(ctx, member, amount)
await ctx.send(f"Removed {amount} warnings from {member.name}!")```
error:
```File "main.py", line 119
await dm.send(embed=em)
^
SyntaxError: invalid syntax```
You never closed brackets in your embed instance
Don't fetch
U can simply do await member.send()
TYY
also this ^
well, it isn't a command sadly for you but to make something case-unsentive you can do this:
im all ears, i feel really stupid π
message = "hello"
response=input("say hello!")
if response.lower()==message:
True
I'm confused because str.upper should make the string all Case which should solve the case-sensitivity issue
the message variable store "hello" all lower, the response is a string taken in input which will be lower case, so even if you write "HELLO" it will be "hello"
str.upper() makes the string all upper case
!e
msg = "hey"
print(msg.upper())
@placid skiff :white_check_mark: Your eval job has completed with return code 0.
HEY
as you see it turns the string upper case
Yeah, the command is all upper-case, so it should make it work
you deleted the message so i can't tell you why
if message.content.startswith(str.upper("$FIRE")):
await message.channel.send(Vehicles["Fire"])
if message.content.startswith(str.upper("$POLICE")):
await message.channel.send(Vehicles["Police"])
so if i have
def setup(bot) -> None: bot.add_cog(Profile(bot))
after my cog
should i be calling setup(bot) in my main.py or something? (or the script that's being run)
Or where is this function called, the function exists in all cog examples
str.uppder() is nothing
watch better this. with str.upper() you are just calling upper method from the string object, but str isn't a variable
so my understanding is
input goes $fire, then the bot makes it all upper case, then checks if the command is written properly. which it should. and then it does its stuff
the function will be called automatically after you load the cog
how to make slash commands
@slate swan
bro i told you like half an our ago
ahh gotha thanks
it erros
show command and errors
yes, you have to load them in your main file or somewhere else but the important thing is that each cogs will be loaded, otherwise they will never work
from disnake.ext import commands
import discord
intents = discord.Intents.default()
intents.members = True
client = commands.Bot(
command_prefix='-',
intents=intents,
case_insenstivive = True
)
client.remove_command('help')
@client.slash_command(description="Shows members", aliases=["membercount"])
async def members(ctx):
await ctx.send(f'{ctx.guild.member_count}')
@commands.has_permissions(ban_members=True)
@client.slash_command(description="Bans a user")
async def BanUser(ctx, user: discord.Member=None, *, reason="The reason was not entered"):
if user is None:
await ctx.send("Please enter the user you want to ban.")
elif user == ctx.message.author:
await ctx.send("You cannot ban yourself.")
elif user.guild_permissions.administrator:
await ctx.send("You cannot ban a admin.")
else:
await user.ban(reason=reason)
await ctx.send(f"Banned {user.name} for {reason} by {ctx.author.mention}")
thanks, appreciate the response, you're helping everyone so i'm sure youll feel exhausted soon haha
you can't use disnake and discord together, disnake is the exact same thing as discord. Read the docs, disnake has intents too and you can launch your bot with disnake too
hahahaha
how to use the intent
https://docs.disnake.dev/en/latest/ this is disnake docs
https://discordpy.readthedocs.io/en/stable/ this is discord.py docs
in the same way you use them with discord
disnake is a fork, they're one and same but disnake has more features
import disnake
from disnake.ext import commands
intents = disnake.Intents.default()
intents.members = True
client = commands.Bot(
command_prefix='-',
intents=intents,
case_insenstivive = True
)
client.remove_command('help')
@client.slash_command(description="Shows members", aliases=["membercount"])
async def members(ctx):
await ctx.send(f'{ctx.guild.member_count}')
@commands.has_permissions(ban_members=True)
@client.slash_command(description="Bans a user")
async def BanUser(ctx, user: discord.Member=None, *, reason="The reason was not entered"):
if user is None:
await ctx.send("Please enter the user you want to ban.")
elif user == ctx.message.author:
await ctx.send("You cannot ban yourself.")
elif user.guild_permissions.administrator:
await ctx.send("You cannot ban a admin.")
else:
await user.ban(reason=reason)
await ctx.send(f"Banned {user.name} for {reason} by {ctx.author.mention}")
client.run("i wont send token")
https://docs.disnake.dev/en/latest/intents.html this is intents use in disnake
https://discordpy.readthedocs.io/en/stable/intents.html this one is intents in d.py
is disnake expected to be the slash command continuation of discord.py?
oh wait now it works
lol i didn't initiate bots like this like for months but it should work
exactly
is a fork so has all the feature of d.py but is maintained
nice, that's good news guess I should make the change soon before i keep developing
it runs but its saying application not respond
the only change is that you have to change all discord in your code into disnake
import disnake
from disnake.ext import commands
intents = disnake.Intents.default()
intents.members = True
client = commands.Bot(
command_prefix='-',
intents=intents,
case_insenstivive = True
)
client.remove_command('help')
@client.slash_command(description="Shows members", aliases=["membercount"])
async def members(ctx):
await ctx.send(f'{ctx.guild.member_count}')
@commands.has_permissions(ban_members=True)
@client.slash_command(description="Bans a user")
async def BanUser(ctx, user: disnake.Member=None, *, reason="The reason was not entered"):
if user is None:
await ctx.send("Please enter the user you want to ban.")
elif user == ctx.message.author:
await ctx.send("You cannot ban yourself.")
elif user.guild_permissions.administrator:
await ctx.send("You cannot ban a admin.")
else:
await user.ban(reason=reason)
await ctx.send(f"Banned {user.name} for {reason} by {ctx.author.mention}")
client.run("e")
show the message in the console
nothing comes in console
yeah and make it slash command friendly for april's change or whatever, I still haven't been developing it that way
what command did you use?
did you pass arguments?
oh wait you don't need the * in async def BanUser(ctx, user, *, reason)
ok
in disnake arguments are taken untill you write them
now it will work rgith?
well, you will not know untill you try
why is the case LikeThis
it's not my command xD
the problem could be the case too
run it and then tell me
@placid skiff do you have a snippet of how you instantiate your bot
if not no worries ill work it out, was just wondering if there was anything else for me to investigate
In theory, will this work?
same error
you can check my GamingNetwork project on my github
but now something come in console
turn the command lower case, do something like this async def ban_user
dunno to be honest
awesome, got a link? or is it blvktvrsier github?
it should be linked to my discord
yes, check my profile
How do we read embeds? On_message ones
that it is, never used that feature before
i changed it into async def ban
i should check the docs but now i start working so I don't have time :L
Oh
i'm just waiting my partner to finish calling routine xD
@placid skiff this is an of the bot error
i read now the error sorry, ctx hasn't the attribute message, as you can see when you digit the command it is deleted and appears in your application response
to retrieve the author you can just do ctx.author
it returns the user or member object which has called the command
ok
did you find it? xD
yeah I did, just trying to work out the easiest way to get it done and basically just implement the
def setup(self): for cog in COGS: try: print(f" loadin {cog}") self.load_extension(f"lib.cogs.{cog}") except NoEntryPointError: print(f" failed to load {cog}\nNo setup found") # except ExtensionFailed: # print(f" failed to load {cog}\nThe extension or its setup had an execution error") else: print(f" {cog} loaded")
part into my code
into my main.py for now haha before i go into making my own inherited bot class
right then π
but ill probs be using yours for a bit as reference so i appreciate the help, thanks again
no problem
thank you
reference to the docs from now on, it really helps when you take the hand of it
remember that disnake use both standard commands and slash one but they doesn't share the same interaction. slash commands use disnake.ApplicationCommandInteraction, commands use disnake.ext.commands.Context
For their purpose is the same they have some differences
ok
Hello,
I installed the package of the fivem, and It writes me the following error:
ModuleNotFoundError: No module named 'fivem'
Please help me,
Thanks
Is it really discord bots related issue?
How did you install it
pip install fivem
And what output did you receive
That it was installed...
Yes, I need it for a discord bot
!pypi fivem
@slate swan what IDE do you use
visual studio code
Have you reloaded it after the installation
you installed it from your console or from visual studio console?
Most likely something is wrong with the package itself but I will check this by myself
Never seen anyone using scripts param in setup.py
console
check if the visual studio interpreter is related to your local python interpreter
How?
Yeah the problem is with the package @slate swan
You can fork it and correct the setup.py
@slate swan you know how to work with github right?
I have this:
`@bot.event
async def on_raw_reaction_add(payload):
print(f"Reaction {payload.user_id}")
guild_id = payload.guild_id
guild = discord.utils.find(lambda g : g.id == guild_id, bot.guilds)
global confirmation
if payload.emoji.name == 'ποΈ':
>>here<<
category = discord.utils.get(guild.categories, id=932890002193547304)
channel = await guild.create_text_channel(name=f"π«οΈ±{payload.member}", category=category)`
I wanna remove the reaction there when it is the right emoji but i cant find anything that works about payload and remove reaction
payload.emoji returns an emoji object, so it has all emoji methods, you can use it to delete the emoji
I am pretty sure you can compare unicode emojis like just emoji == 'π'
why not use the unicode?
urls work too
