#discord-bots
1 messages · Page 802 of 1
@sick birch :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 2, in <module>
003 | NameError: name 'x' is not defined
your variable has to come before when you use it
@client.event
async def on_member_update(before, after):
guild = client.get_guild(932840827212931123)
role = discord.utils.find(lambda r: r.name == 'promoter', guild.roles)
if ".gg" in str(after.activity.name):
await after.add_roles(role)
if ".gg" not in str(after.status.name):
await after.remove_roles(role)```
perfect
yay !
Though I think something might be wrong with the utils.find
Perhaps using guild.get_role(id)? It's more reliable
File "main.py", line 63, in on_member_update if ".gg" in str(after.activity.name): AttributeError: 'NoneType' object has no attribute 'name'
But if you really want to use the name, the first argument is an iterable, the 2nd is an attribute
i get this error every now and then
That could happen if the user doesn't have a status
id is better
@client.event
async def on_member_update(before, after):
guild = client.get_guild(932840827212931123)
role = guild.get_role(935258354689925150)
if ".gg" in str(after.activity.name):
await after.add_roles(role)
if ".gg" not in str(after.status.name):
await after.remove_roles(role)```
awesome
Yes
@commands.command(help = 'Ban a member!')
@commands.has_permissions(ban_members = True)
async def ban(self, ctx, member : discord.Member = None, reason=None):
if member == None:
await ctx.reply("please mention a user")
else:
await member.ban(reason = reason)
embed = discord.Embed(description= f"✅ **{member.display_name}#{member.discriminator} banned!**", color=discord.Color.green())
await ctx.send(embed=embed)```
how do i ban by ID?
Robin helper be like
If you have the ID you probably have the object
You're doing this right
At least the banning part
:D
but i cant ban unless they are in the server
That's how banning works
carl bot bans when they arent?
Oh you mean just adding someone to the banned list?
yes
you're too quick, snatching the words out of my head smh
!d discord.Guild.ban
await ban(user, *, reason=None, delete_message_days=1)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Bans a user from the guild.
The user must meet the [`abc.Snowflake`](https://discordpy.readthedocs.io/en/master/api.html#discord.abc.Snowflake "discord.abc.Snowflake") abc.
You must have the [`ban_members`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.ban_members "discord.Permissions.ban_members") permission to do this.
Haha feel free to help though
before I even start typing you finish the sentence for me
how am I supposed to
where would i add this?
I'm a bit rusty at dpy rn lol
or would i have to make a separate command
anyway @pallid mango discord.Guild.ban() takes a discord.abc.Snowflake
well, in the member.ban()?
what is the problem here? the status wont show
You can make your own like so:
mySnowflake = discord.Object(id)
your code should work iirc
and pass that into ban(0
whats snowflake
camelCase
await client.change_presence(activity=discord.Activity(type=discord.ActivityType.watching, name=""))
Don't change your status on_ready
😡
give him a ticket, officer :p
I think you should actually watch these variable names though
what should I change to though?
this was working earlier
You're inadvertently teaching people bad practices
there we go
os.system is not async
- dont change in on_ready
we're partners in...PEP8 now
An ID, you can get the time it was created from it. Most things in discord are snowflakes: messages, channels, guilds, users, members, you name it. Hence why it's an ABC, an abstract base class. Most things in d.py subclass discord.abc.Snowflake in one way or another
use the kwarg in commands.Bot
so what the correct change be?
ok
Are you on linux? clear doesn't work on windows iirc
thanks robin
👍
!d discord.ext.commands.Bot
class discord.ext.commands.Bot(command_prefix, help_command=<default-help-command>, description=None, **options)```
Represents a discord bot.
This class is a subclass of [`discord.Client`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client "discord.Client") and as a result anything that you can do with a [`discord.Client`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client "discord.Client") you can do with this bot.
This class also subclasses [`GroupMixin`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.GroupMixin "discord.ext.commands.GroupMixin") to provide the functionality to manage commands.
im on a private panel using python
Just beware clear won't work on all systems, either way it's not async so avoid using it
so change the code to what?
And since on_ready can get called multiple times for no reason, it can clear your console for no reason which is bad if there are errors you haven't looked at yet
!d discord.Client
class discord.Client(*, loop=None, **options)```
Represents a client connection that connects to Discord. This class is used to interact with the Discord WebSocket and API.
A number of options can be passed to the [`Client`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client "discord.Client").
like I said, to what tho, cause this was fine an hour ago
works for me
That's the thing, it's unpredictable and sometime will work sometimes won't
it can also prevent your bot from fully connecting to the gateway, since you can get kicked before you even get the GUILD_CREATE events
in short: only thing you should do in on_ready() is print
hmm, im just trying to get this fixed to continue on an unmute command
nothing else, no exceptions
@commands.command(help = 'Ban a member!')
@commands.has_permissions(ban_members = True)
async def ban(self, ctx, member : discord.Member = None, reason=None):
mySnowflake = discord.Object(id)
if member == None:
await ctx.reply("please mention a user")
else:
await member.ban(reason = reason)
embed = discord.Embed(description= f"✅ **{member.display_name}#{member.discriminator} banned!**", color=discord.Color.green())
await ctx.send(embed=embed)```
pass it into the activity kwarg of your commands.Bot
id will have to be the ID of the user you want to ban
whats a kwarg?
i am confused on what you want me to do
!args-kwargs
*args and **kwargs
These special parameters allow functions to take arbitrary amounts of positional and keyword arguments. The names args and kwargs are purely convention, and could be named any other valid variable name. The special functionality comes from the single and double asterisks (*). If both are used in a function signature, *args must appear before **kwargs.
Single asterisk
*args will ingest an arbitrary amount of positional arguments, and store it in a tuple. If there are parameters after *args in the parameter list with no default value, they will become required keyword arguments by default.
Double asterisk
**kwargs will ingest an arbitrary amount of keyword arguments, and store it in a dictionary. There can be no additional parameters after **kwargs in the parameter list.
Use cases
• Decorators (see !tags decorators)
• Inheritance (overriding methods)
• Future proofing (in the case of the first two bullet points, if the parameters change, your code won't break)
• Flexibility (writing functions that behave like dict() or print())
See !tags positional-keyword for information about positional and keyword arguments
@commands.command(help = 'Ban a member!')
@commands.has_permissions(ban_members = True)
async def ban(self, ctx, member : discord.Member = None, reason=None):
mySnowflake = discord.Object()
if member == None:
await ctx.reply("please mention a user")
else:
await member.ban(reason = reason)
embed = discord.Embed(description= f"✅ **{member.display_name}#{member.discriminator} banned!**", color=discord.Color.green())
await ctx.send(embed=embed)```
Why are you getting an object when you already have a discord.Member object?
pass in your status to commands.Bot rather than doing it on_ready
where?
your bot instance
idk
yeah, but where is that?
only you would know
Also why are you making member None?
most likely at the top, right below your intents
You're manually making it a required argument
?
Why not let discord.py handle it for you?
idk tbh
i followed tut on this ban command
what?
just personalized it
yep
Also, if you send member it sends their name and discrim
So no need to get the attributes
your bot instance? the driver for your bot?
bot = commands.Bot(..)
Should look like that
yes but you would need a bot instance for that to work
oh no, its that one
yep, that's where you add the activity to
Hi, I am trying to get access to all the tracks in a spotify playlist using spotipy python.
issue is that i only can extract the first 100 tracks from the playlist
when i searched around on how to get the full tracks, it seems that i have to authorize but i am using SpotifyClientCredentials with my client ID and client secret but i still get the first 100 only and the SpotifyOauth or whatever it was called requires a redirect_uri which i don't need, i kept searching for any documents or solutions and i found out that i can use playlist = spotify.playlist_tracks(playlist_url, offset=number, limit=number2) inside a while loop while increasing the offset number so i can get the next 100 and etc but all it does is keep repeating the first 100 songs till it exists the while loop
I am not sure if there is a way with this library and i am open to any recommendations, Thank you
also i see that playlist_tracks is being crossed out like playlist_tracks, idk why
Not related to discord bots, you'd have better luck either in #python-discussion or claim yourself a help channel
No prob
okay
so can i clear this ban command up a lil bit
@commands.command(help = 'Ban a member!')
@commands.has_permissions(ban_members = True)
async def ban(self, ctx, member : discord.Member = None, reason=None):
mySnowflake = discord.Object()
if member == None:
await ctx.reply("please mention a user")
else:
await member.ban(reason = reason)
embed = discord.Embed(description= f"✅ **{member.display_name}#{member.discriminator} banned!**", color=discord.Color.green())
await ctx.send(embed=embed)```
pep8 said i have extra stuff
No need to get an object if you already have a discord.Member object
how to take a message i send to my bot in dm so then bot sends it to a channel?
simpler to make a repeat command
nobody can really see what u said, the bot deletes it fast enough
but for example bot sends it to channel when users cant send messages
but do you know how do i take received DM message?
Commands should work in dms, no?
Try
i owe you one
They should
what did I do?
!d discord.ext.commands.dm_only
@discord.ext.commands.dm_only()```
A [`check()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") that indicates this command must only be used in a DM context. Only private messages are allowed when using the command.
This check raises a special exception, [`PrivateMessageOnly`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.PrivateMessageOnly "discord.ext.commands.PrivateMessageOnly") that is inherited from [`CheckFailure`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure").
New in version 1.1.
was it you that helped me
This restricts it to a dm only command
😳
no
How do you add those lines things?
?
oh its an emoji
external emoji
sick right?
i can give it to you in dms
no problem
._.
@final iron
can i get the pfp of the bot
dude i have never seen someone use nextcord before lmfaooo
no it’s not related to u
bot.user.avatar_url. bot.user.avatar.url if you're on 2.0
idk if im on 2.0
just saying i was tryna help someone earlier and they were using discord.py code with nextcord
i dont think so honestly
okay so every since i added py invites = await ctx.guild.invites() for inv in invites: if inv.code == invite.code: return invto my command it's just stopped responding completely and I'm not getting any errors . This is my code. I'm assuming I've structured my for and if statements wrong to get it stuckpy @commands.command(description = "Get some information about a invite.", usage = "inviteinfo", aliases = ["invitestats", "ii"],) async def inviteinfo(self, ctx, invite: discord.Invite): invites = await ctx.guild.invites() for inv in invites: if inv.code == invite.code: return inv embed = discord.Embed(title = f"Server invite: {invite.code}", description = f"Invite created <t:{int(inv.created_at.timestamp())}:R>", colour = ctx.author.colour, url = invite.url) embed.set_author(name = f"ID: {invite.id}", icon_url = invite.guild.icon_url) embed.add_field(name = "Inviter", value = f"{invite.inviter.mention}|{invite.inviter.mention}" if invite.inviter else "Unknown") embed.add_field(name = "Uses", value = f"{invite.uses}/{'Infinite' if invite.max_uses == 0 else invite.max_uses}", inline = True) embed.add_field(name = "Expires", value = f"<t:{int(invite.max_age.timestamp())}:R>", inline = True) embed.add_field(name = "Temporary", value = f"{invite.temporary}", inline = True) embed.add_field(name = "Revoked", value = f"{invite.revoked}", inline = True) embed.add_field(name = "Channel", value = f"{invite.channel.mention}", inline = True) await ctx.reply(embed = embed)
Try print(discord.__version__)
!d discord.Invite.code
The URL fragment used for the invite.
im back to discord.py dev and i forgot too many things
Why are you returning inv?
returning essentially kills your function
So it would be avatar_url
kk
oh, i always get the function ending's mixed up, I'm trying to return inv bc I don't want to have to ident the embed (minor thing) but I still need to get inv out of the function so i cna use it in py embed = discord.Embed(title = f"Server invite: {invite.code}", description = f"Invite created <t:{int(inv.created_at.timestamp())}:R>", colour = ctx.author.colour, url = invite.url)
Just indent it
👍
bot.user.avatar_url
kk
bot.user is a discord.user.ClientUser object
i shall follow the advice of the oh great master pep8 compliance officer
!d discord.ext.commands.Bot.user
property user: Optional[discord.user.ClientUser]```
Represents the connected client. `None` if not logged in.
!d discord.user.ClientUser
class discord.ClientUser```
Represents your Discord user.
x == y Checks if two users are equal.
x != y Checks if two users are not equal.
hash(x) Return the user’s hash.
str(x) Returns the user’s name with discriminator.
!d discord.User.avatar.url
No documentation found for the requested symbol.
im soo proud of my son omg
oof
im planning to make bots for fiverr, is that a good idea?
dont return and add 2 tabs indent so the code will be inside the if statement
It's not a bad idea
@bot.command()
async def commands(ctx):
embed = discord.Embed(
title=f"Commands",
description=f"""
>help (shows this command)
>quote
>hello
>cmds
>tictactoe (mention) (mention)
>tmg
>slap (mention)
>cf (coinflip)
""",
set_thumbnail(url="./tmgmidvitelogonowords.png")
colour=0x3D9AF2)
await ctx.send(embed=embed)```
I doubt you'll get a lot of purchases
i've thought of something like that
^
SyntaxError: positional argument follows keyword argument```
thats my biggest thought lol. i want to be able to get to the point of doing more specific bots
Why does this error?
make an nft bot and youll get orders in no time
Remove set_thumbnail
or else you can make a mass dm bot
!d discord.Embed.set_thumbnail
set_thumbnail(*, url)```
Sets the thumbnail for the embed content.
This function returns the class instance to allow for fluent-style chaining.
Changed in version 1.4: Passing [`Empty`](https://discordpy.readthedocs.io/en/master/api.html#discord.Embed.Empty "discord.Embed.Empty") removes the thumbnail.
That's how you set the thumbnail
what's fiverr
set_thumbnail("./tmgmidvitelogonowords.png", url) like this?
a website where people post things like "buy my service"
and then people buy it
go to fiverr.com, you'll understand
already done following pep 8's advice,
now my next issue; py embed.add_field(name = "Expires", value = f"<t:{int(invite.max_age.timestamp())}:R>", inline = True)is producing py AttributeError: 'NoneType' object has no attribute 'timestamp'which I understand since max_age is How long the before the invite expires in seconds. A value of 0 indicates that it doesn’t expire., is there a way I can wrap this seconds value in timestamp markdown, I assume I'll need to convert it to epoch time first
so how
can i sell websites there too??
ofc u can
Use set_thumbnail on your Embed object
thats really nice looking
no
Make different categories
ok wait ill try putting the bots icon
good idea
good idea
embed = discord.Embed.set_thumbnail("./tmgmidvitelogonowords.png", url)
now isnt that fucking delightful to look at 
No
You use the set_thumbnail method on your instance of the Embed object
embed.set_thumbnail()
embed.set_thumbnail("./tmgmidvitelogonowords.png", url)
!d discord.Embed.set_thumbnail
set_thumbnail(*, url)```
Sets the thumbnail for the embed content.
This function returns the class instance to allow for fluent-style chaining.
Changed in version 1.4: Passing [`Empty`](https://discordpy.readthedocs.io/en/master/api.html#discord.Embed.Empty "discord.Embed.Empty") removes the thumbnail.
looks dope
There is only 1 kwarg
Check the docs out
i found out what is it and its interesting
ikr
@pallid mango I used 'if isinstance(message.channel, discord.DMChannel):' and it worked
rate this out of ten
wasnt even sure of what u needed ngl
7/10
alr what can i change
i thought u just wanted a way to send messages as a bot
yes
well. proper spelling and grammar. new emojis, and add a pfp
well personally i like repeat command
i simply do .repeat <message> and bot deletes message and resends itself
can u tell me where the grammar errors are
also ill update the emojis
8/10
you'll want Bots Dictionary
yes, and no apostrophe
Well you can delete it with ctx.message.delete
i recommend this https://fontawesome.com/
i have code
kk
i was just recommending to the other person
Ah
how do i use bot.wait_for and a function to check if the reaction is pressed to then do something
in my case i want it to edit the embed
ping me
Aside from your variable naming, nothing
i told you
customize it in font awesome
wait
the icons arent centered
now they are
i made it on pixlr
but u said font awesome afterwards
ill use fontawesome next
you download the svg and color it on a svg editor
ez
nice
alright i need to use bot.wait_for and a function that checks if the reaction is pressed and if a certain emoji is pressed something happens
Check out the gist
It will explain everything
If you want I guess
stella subclasses help cmd 99%
nvm 100%
why do you guys make discord bots
just curious
It was my first project
i make it for my server
this too
I enjoyed it
saw all those cool features and i wanted to learn python so i started doing them dont do them anymore but i just hangout here helping others lol
python is great
very simple
i don't do much python dev anymore, but i still help
rlly
@slate swan I want to try contibuting to your project. How would I setup your code to make sure its working without errors?
which project is this?
twitter api wrapper
cool
what needs to be done for that
just make a dev twitter account so you can have the bare token of auth
which is used for most request
not all*
okimii give me yours
So akeno = AkenoClient("my token here")?

yes
What do I pick
will you give the data you receive to the goverment?
I understand that
See, I wont be directly giving data to the government but they're free to get it
Invite me
alr
im intrigued by this idea but dont know if its something i be helpful at lol
aight, ill need a bit of help getting everything for it set up
can tasks.loop take a guild argument?
gib example
your computer 🙂
You should try heroku but I only recommend if you want free alternative
Most free hosting aren't very good, I would say go with one of the larger hosts such as AWS EC2 or google cloud hosting since they're reliable and in the case of AWS it's very easy to scale
A raspberry pi is also a very good choice, while it's a heavy initial investment, it can be a pretty decent host while your bot isn't insanely huge, but keep in mind it doesn't scale either
lets say paid then?
ignore robin, he's only saying aws because he gets it free 😡
Sure, personally I'm working on a project where we use multiple AWS services and it's very good
lucky robin simping
lmao
check pins
Keep in mind though AWS is a bit more expensive than the others
But they also have a bunch of other services and they tie together easily inside the ecosystem
how do i add roles using my discord bot
!d discord.Member.add_roles
await add_roles(*roles, reason=None, atomic=True)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Gives the member a number of [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role")s.
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, and the added [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role")s must appear lower in the list of roles than the highest role of the member.
that’s not how it works
await add_roles(discord.Role,reason=None,atomic=False)
how do i make a discord.Role arg then
yaml = YAML()
with open("./Config.yml", "r", encoding = "utf-8") as config_file:
config = yaml.load(config_file)
class OpenInterest(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.openinterest_btc_5.start()
@tasks.loop(seconds = 3000)
async def openinterest_btc_5(self):
openinterest_channel = await self.bot.fetch_channel(config["Channels"]["OpenInterest"])
btc_coinalyze_link = config["CoinAlyze"]["BTC"]
btc_5_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
oi_btc_binance_api = "https:/fapi.binance.com//fapi/v1/openInterest?symbol=btcUSDT"
json_btc_oi_5 = response = requests.get(oi_btc_binance_api)
json_btc_oi_get_5 = json_btc_oi_5.json()
btc_binance_oi_5 = float(json_btc_oi_get_5["openInterest"])
del btc_5_list[0]
btc_5_list.append(btc_binance_oi_5)
result = (statistics.stdev(btc_5_list))
embed = discord.Embed(
title = " Open Insterest Alert",
description = f"Variation Detected !",
color = config["Embed"]["Color"])
embed.set_footer(text = config["Embed"]["FooterText"],
icon_url = config["Embed"]["IconURL"])
embed.add_field(name = "Open Interest Data", value = f"{result}", inline = False)
await openinterest_channel.send(embed = embed)
def setup(bot):
bot.add_cog(OpenInterest(bot))
print("OpenInterest Cog: Logged")
``` So... I have this running but I think a file cannot be updated while running right??? Considering that, will this cog work? Thanks in advance 🙏
There's no reason a file can't be updated while the bot's running, though you should use aiofiles since it's not blocking
Hi, I have a task (loop) which repeats every 5 minutes.
However 1-2 days the task stops and I get this error:
[Errno 104] Connection reset by peer```
Every other task or command works fine but not this loop. Is there a way I can fix this?
Restart the bot.
Could you develop a bit more please? Much appreciated 🙏 🙂
Want an invite to the server?
sure, why not
That's not a solution
Have you tried at least? Are you having the same error?
Cant I just have everything in the same file?
I always restarted the bot when this error accurd. That's not a solution it just happens everytime after 1-2 days
are you storing and retrieving data from json file?
if so, for one consider using a data, but aiofiles is not blocking so consider using that instead
here the file actually closes since you're using a context manager
it's opened, all the contents are read, then closed
the with open() is all outside
It's not writing because you actually have to dump the contents back into the yaml file
Well then lemme send the full code I edited some parts before sending it here
nono this is alright
i know what the issue is
yeah it reads all the contents of the file, stores it, then immediately closes it
so the file isn't open at all
I should create a secondary python file where I append and delete and do all the stuff I want?
the reason it's not showing up in the file is because you need to dump the contents back in
1.- What's that
2.- How can I do it
🤣
the config variable is just a copy
never heard about dumping contents back in
not the actual file itself
but the problem isnt the config file
then?
the list is causing the problem I think
what is the problem though
I have the same format of file with the config outside the class and it works
Guys is there a way i could have someone send an image with a command then turn it into a link?
right but what is the problem?
All attachments on discord are links, you don't have to turn it into a link
And that my friend
Ty for giving my common sense back

I'm expecting the list to be updated every 3000 seconds and then send the stdev of the list in an embed
there we go
but thats not happening, nothing is happening basically
by list what do you mean?
btc_5_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
odd it should be updating since it's just a variable
its just not working, no traceback
try printing the list
idk why, I checked that its logging correctly, etc
okay sure
print(btc_5_list) and see if it's different each time
but its not even sending the stdev the first time, but ok I'll print it right now
not updating
and its not even sending the embed to the openinterest_channel
idk I give up 🤷♂️
This isn't very async
lmao
says who
maybe async is just an idea
what is async
who is async
i think caeden drank to much tea
what is real
👀
Says requests.get()
its 3am
go to sleep
what if requests is a method that makes a request with aiohttp
true that

help\

@client.slash_command(description="Set up a mod log channel.")
async def SetModLog(ctx, channelid):
db = sqlite3.connect('channels.db')
cursor = db.cursor()
cursor.execute("INSERT INTO channels VALUES (?, ?)", (channelid, ctx.guild.id))
db.commit()
why this thing not working
@commands.command(brief="Checks status of servers being monitored", usage="status")
# while True:
# time.sleep(30)
async def status(self, ctx) -> None:
"""Returns an embed showing the status of each monitored server"""
embed = embeds.Embed(
title="**Estado De Los Servidoress**",description="Este es el estado actual de nuestros servidores, este mensaje se actualizará cada cierto tiempo." ,color=16711680 if self.currently_down else 65287
)
for i in get_servers():
if i["address"] in self.currently_down:
downtime = str(timedelta(seconds=self.currently_down[i["address"]]))
embed.add_field(
name=f"{i['name']} ({i['type']})",
value=f":red_circle: Sin Conexión ({downtime})",
#value=f":red_circle: {i['address']} ({downtime})",
#value=f":red_circle: Oculto ({downtime})",
inline=True,
)
else:
embed.add_field(
name=f"{i['name']} ({i['type']})",
value=f":green_circle: En Línea",
#value=f":green_circle: {i['address']}",
#value=f":green_circle: Oculto",
inline=True,
)
msg = await ctx.fetch_message(939283098821087312)
await msg.edit(embed=embed)
# await ctx.send(embed=embed)
I have this code, its a command to monitor the status of some servers, what it does is that when I run the command a message updates with the status of each server and if it is online or offline it shows, that works.
The thing is that I want to make this, like a js setInterval, that i just run the command once and it automatically re-runs the command every 30 seconds, I've been searching for serInterval python codes but all of them weren't working.
PData
sql injection go brrrr
?
channelid is not typehinted as anything?
As in the SQL statement
how to fix
Like, you won't be able to send a DROP TABLES statement
its a slash command i entered it
oh
i must make it to integer?
i see
probably could find a way
Mmm the parameterised statement means that it would be santised
You could exploit this command if they used f-strings instead
ok
@client.slash_command(description="Set up a mod log channel.")
async def SetModLog(ctx, channelid):
db = sqlite3.connect('channels.db')
cursor = db.cursor()
cursor.execute("CREATE TABLE IF NOT EXISTS channels(guildid INTEGER, channelid INTEGER)")
cursor.execute("INSERT OR IGNORE INTO channels VALUES (?, ?)", (channelid, ctx.guild.id))
db.commit()
this works?
yeah in terms of sql injection thats not a problem, but you are inserting strings into an integer field
sqlite3 is blocking
i dunno how to use tatr
It's just sqlite3 with await's
ok
consider using a discord.TextChannel converter and accessing the id from that so dpy can verify that the given id is a valid channel
i.e. async def SetModLog(ctx, channel: discord.TextChannel):
db = sqlite3.connect('channels.db')
cursor = db.cursor()
cursor.execute("CREATE TABLE IF NOT EXISTS channels(guildid INTEGER, channelid INTEGER)")
cursor.execute("INSERT OR IGNORE INTO channels VALUES (?, ?)", (channelid, ctx.guild.id))
db.commit()
how to convert into aiosqlite
ok
dont create a new instance of db each time
ok
@client.slash_command(description="Set up a mod log channel, this command needs to be sent in the channel you want the modlogs to be sent.")
async def SetModLog(ctx, channelid: disnake.TextChannel):
db = sqlite3.connect('channels.db')
cursor = db.cursor()
cursor.execute("CREATE TABLE IF NOT EXISTS channels(guildid INTEGER, channelid INTEGER)")
cursor.execute("INSERT OR IGNORE INTO channels VALUES (?, ?)", (channelid, ctx.guild.id))
db.commit()
like this?
Fix your function naming. Functions should be written in snake_case
snake_case?
adding to this, you can add the db as a bot var and connect to it before running your bot, e.g. ```py
bot = MyBot()
async def main():
async with aiosqlite.connect('mybot.db') as db:
bot.db = db
await bot.start(TOKEN)
somewhere else
@bot.command()
async def mycommand(ctx):
cursor = await bot.db.execute('SELECT something FROM a_table')
row = await cursor.fetchone()
asyncio.run(main())```
Yes
so i put that code?
asyncio.run(main())
client.run(token)
instead of client.run i put asyncio.run?
sure, client.start() is basically the async version of client.run
@client.slash_command(description="Set up a mod log channel, this command needs to be sent in the channel you want the modlogs to be in.")
async def SetModLog(ctx, channelid: disnake.TextChannel):
cursor = await client.db.execute('SELECT something FROM a_table')
row = await cursor.fetchone()
this creates a table or i have to write the code
you can create the table just before your bot starts, easier than having to create it anywhere your commands may need it
ok
You might want to add a command that allows you to execute sql within discord
Makes your life so much easier
does it have to be in the main()
Well async code has to be executed in a function
how to do tat
By putting it in a function?
I'm getting the feeling you havent learned python yet
I would highly recommend you do so
discord.py is not a beginner project
no its just that im not very good at english
async def main():
async with aiosqlite.connect('channels.db') as db:
client.db = db
cursor = db.cursor()
await client.start(token)
cursor.execute("CREATE TABLE IF NOT EXISTS channels(guildid INTEGER, channelid INTEGER)")
like this
sure, but you need to commit it as well
and dont use the async with method to bind it with the Bot
client.db = await aiosqlite.connect('database')
``` is all you need
iirc there's nothing wrong with using async with, at least it explicitly lets the connection get closed when the bot stops
sure, but thats a quite inefficient way, and the connection will be lost as soon as the main function is completed
ok
what else way?
i mentiond that in the next message
i highly doubt its an "inefficient" way, and in their case both are equivalent
not in the sense of connection, but they are doing something in 3 lines which can be done in a single one.
and ofcourse, this
@client.slash_command(description="Set up a mod log channel, this command needs to be sent in the channel you want the modlogs to be in.")
async def SetModLog(ctx, channelid: disnake.TextChannel):
client.db = await aiosqlite.connect('channels.db')
cursor = await client.db.cursor()
cursor.execute("CREATE TABLE IF NOT EXISTS channels(guildid INTEGER, channelid INTEGER)")
like this?
its only two lines, async with and client.db = db, of which both are equally as readable and isnt worth a debate over
which waydo i do
well you already typed it, leave it as that
oh wait you placed it inside your command
i can remove it
why place it in a command, every time the command runs a new connection would be made..
and the old one wont be closed either
true :3
i want it only to be made if the user want to set the mod log channel
then you would like using the async with method, and there's no need to use it as a botvar
@command()
async def my_cmd(..
async with aiosqlite.connect() as db:
# db is the Connection
...
# connection gets closed as soon as your are outside the with statement```
this will close the connection as soon as your work is done
take it as a reference.. ¯_(ツ)_/¯
ok
the @command is @client.command?
yea, you could say that
ok
@client.slash_command(description="Set up a mod log channel.")
async def SetModLog(ctx, Channelid: int):
async with aiosqlite.connect('mybot.db') as db:
client.db = db
cursor = db.cursor()
await client.start(token)
cursor.execute("CREATE TABLE IF NOT EXISTS channels(guildid INTEGER, channelid INTEGER)")
```like this?
why would you start the bot inside a command??
yea it seems ok
ok
everytime you perform a "write" operation, you need to commit into the database
cursor.execute("INSERT INTO channels VALUES(?, ?)", (ctx.guild.id, Channelid))
i also add this?
depends on what you want to do,.
@client.slash_command(description="Set up a mod log channel.")
async def SetModLog(ctx, Channelid):
async with aiosqlite.connect('channels.db') as db:
client.db = db
cursor = db.cursor()
cursor.execute("CREATE TABLE IF NOT EXISTS channels(guildid INTEGER, channelid INTEGER)")
cursor.execute("INSERT INTO channels VALUES(?, ?)", (ctx.guild.id, Channelid))
await db.commit()
whyh when i run this command its not making a new table

errors?
nope
how do you know that the table is not getting created.?
you need to reopen the database file after commiting.
how to do thar
in your browser
yeah i did
i dont even think the code went thru
@client.slash_command(description="Set up a mod log channel.")
async def SetModLog(ctx, Channelid):
async with aiosqlite.connect('channels.db') as db:
client.db = db
cursor = db.cursor()
cursor.execute("CREATE TABLE IF NOT EXISTS channels(guildid INTEGER, channelid INTEGER)")
cursor.execute("INSERT INTO channels VALUES(?, ?)", (ctx.guild.id, Channelid))
await db.commit()
print("done")
it doesnt print done
add a print statement to check if the slash command gets executed or not
oh
did you use that command 🤨
yes
show
You need to respond
is that disnake? ¯_(ツ)_/¯
yes
It should still be printing
it didnt print
oh
He's using sqlite3
no
i changed to aiosqlite
Oh
@client.slash_command(description="Set up a mod log channel.")
async def SetModLog(ctx, Channelid):
async with aiosqlite.connect('channels.db') as db:
client.db = db
cursor = db.cursor()
await cursor.execute("CREATE TABLE IF NOT EXISTS channels(guildid INTEGER, channelid INTEGER)")
await cursor.execute("INSERT INTO channels VALUES(?, ?)", (ctx.guild.id, Channelid))
await db.commit()
print("done")
```everything has to be with await?
even the clinet.db
ok
👀
also, why do you use client.db when you dont need a permanent connection
you dont need to do that
Hm u should open it once only yk
ok
unless you want to keep a connection established
Gys help
show your current code
You never added an if statement
you dont have an if
okkk
@client.slash_command(description="Set up a mod log channel.")
async def SetModLog(ctx, Channelid):
async with aiosqlite.connect('channels.db') as db:
cursor = db.cursor()
await cursor.execute("CREATE TABLE IF NOT EXISTS channels(guildid INTEGER, channelid INTEGER)")
await cursor.execute("INSERT INTO channels VALUES(?, ?)", (ctx.guild.id, Channelid))
await db.commit()
print("done")
If the database is not found in the current directory it creates a new one
Confirm its not doing that
await db.cursor
and dont use f strings in sql 💀
but theres no f string
He's not
pls help
huh
you’re missing a single quote in line 17
Oh
yea i read it wrong
It's just freezing?
@client.slash_command(description="Set up a mod log channel.")
async def SetModLog(ctx, Channelid):
async with aiosqlite.connect('channels.db') as db:
cursor = await db.cursor()
await cursor.execute("CREATE TABLE IF NOT EXISTS channels(guildid INTEGER, channelid INTEGER)")
await cursor.execute("INSERT INTO channels VALUES(?, ?)", (ctx.guild.id, Channelid))
await db.commit()
print("done")
doesnt create a table and doesnt priunt
You got an error handler eating errors?
like ifinstance?
Yeah
@client.event
async def on_slash_command_error(interaction, error):
if isinstance(error, commands.MissingPermissions):
embed=disnake.Embed(color=0xb30000, title="Error", description="You do not have the permission to use this command.")
await interaction.send(embed=embed)
Add:
else:
traceback.print_exception(type(error), error, error.__traceback__)
To the end of that
Make sure to import traceback
Still no working\
Is there an error?
no
Did you restart your bot?
Yeah
ok i will send in dm
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 i dpnt wanna leak it
Leak what
its a big code
Use this
i send u link i n dm
but people will look it ):
Ok and?
len(bot.cogs)
bot is your instance of commands.Bot
Therefore you can access all your attributes and methods of the Bot class with bot
Show the code
You probably did the same thing as before
You shouldn't be doing anything in on_ready
It can be called multiple times
where should i put it
The command should be working
and if you make request it will disconnect you from the gateway
why it not
Can we see the code?
well you cant add a method to that kwarg
you probably did discord.Color.< color name> and forgot to add ()
discord.Color.random()
i mean yeah you can but you need to call it like you said
hi
@client.slash_command(description="Set up a mod log channel.")
async def SetModLog(ctx, Channelid):
async with aiosqlite.connect('channels.db') as db:
cursor = await db.cursor()
await cursor.execute("CREATE TABLE IF NOT EXISTS channels(guildid INTEGER, channelid INTEGER)")
await cursor.execute("INSERT INTO channels VALUES(?, ?)", (ctx.guild.id, Channelid))
await db.commit()
print("done")
anyone know why it no work?
because channelid needs to be an integer and you try to push a string into it
sure, but thats not how slash options work ig
well waht should i put ti as
anyone help
what do i put it instead
It still doesnt work ):
https://paste.pythondiscord.com/pitaligapo.py
check my full code
not related to the issue but you should put the bot token in a .env file and pull it from the file istead of having it open in the code
typehint channelid to int
channelid: int like thiso?
ye.
ok
should i try doing it with sqlite3
and, typehinting it made it worse cuz it saying not a valid integer
936246330286809101
when are people actually gonna learn python properly before using discord.py
Read the error, you missed an argument when you invoked the command .donated @User 1 2
Never
Are you loading the cog?
So it's sending but not editing?
discord bots are something cool which people would like to try so theres always gonna be that someone that wants to take a shortcut
¯_(ツ)_/¯
You got an error handler eating up errors?
Hi
Can anyone tell me how to make a command which will unban everyone in discord ban list of server
!d discord.Member.unban and just check the ban list iirc theres something that returns a list of bans i think it was Guilds.bans im not sure
await unban(*, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Unbans this member. Equivalent to [`Guild.unban()`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild.unban "discord.Guild.unban").
!d discord.Guild.bans
await bans()```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Retrieves all the users that are banned from the guild as a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.9)") of [`BanEntry`](https://discordpy.readthedocs.io/en/master/api.html#discord.BanEntry "discord.BanEntry").
You must have the [`ban_members`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.ban_members "discord.Permissions.ban_members") permission to get this information.
yep
How to make a mass unban command
Hello?
;-;
Idk about cogs sorry
this verges on a rule 5 situation so not many people will likely help with your question
add a print statement and see if its even calling the code or getting to certain parts of it
Hey guys I am trying to build a discord bot and want to ask you all can I build a discord bot for my friends server like so far I have noticed that one have to set up a bot using discord settings in their own server but how can I build a bot for someone else's server?
a) Messages have a created_at attribute, not a timestamp.
b) The datetime object you get from that will not have anything called total_seconds(). You have to look for the seconds parameter.
There should be authorization issues in someone else's server
As long as the user has the permission to add bots to that server, they can use the auth link to invite the bot
Okay so not everyone has the permision to add bots?
No, only people who've been given a role with the permission
nah, they should cause it's annoying
Do you know any video that I can watch for this task of sending invite to bot?
You're asking how you can invite your bot to a server?
Yeah not to my server but someone else's
you need to get the oauth url and send that to whoever has perms to add bots to the server and they add it
A server is a server. Who owns it does not matter as long as the person has the permissions to invite it to the server.
If you're just getting started with bots, you can get more info on that from the docs.
https://discordpy.readthedocs.io/en/latest/discord.html#inviting-your-bot
Alright and should code it in Repl or my local ide since I was watching a tutorial in freecodecamp there they said that if you want to make sure that your bot run even after you close your computer then save the code in cloud
dont use repl
Thank you so much for this
you can do it
i think repl is the bad one. there is 1 common one people always ask or say they use thats bad
Then how will the bot remain active if I will close my computer
use a host/vps
put it on a VPS
iterate through it lol
Do we have a tag for hosting here?
no
No idea what that thing is but I will figure it out
Aaand can we create tags? I'm assuming not
First of all I will have to learn asynchronous programming
you cant iterate through Member.unban...
Tags are overrated
Nope u can't.
make an issue on github
VPS
!source
@client.command(pass_context=True)
async def unbanall(ctx):
guild=ctx.message.guild
ban_list=await client.get_bans(guild)
await client.say('Unbanning {} members'.format(len(ban_list)))
for member in ban_list:
await client.unban(guild,member)
Why it doesnt unban everyone in ban list?
why copy code
old code
Then
very old
What to do -_-
who said about iterating through Member.unban?
Client.unbanisn't even a thinganymore
Lol
@timid wagon go work on the guide
how to make a mass ban command?
iterate through it lol
?
Then how to unban everyone in ban list
I'm rn hosting my bot on Heroku bot the ping is high can anyone suggest me any other free hosting sites like heroku?
scroll up
Dude, stop
iterate through Guild.bans, use the unban method on em'
No thanks
I'll work on the guide when I want to. Forcing me to create content won't get you anywhere
Rip
Bruh give docs or something. I didn't understand
!d discord.Guild.bans
await bans()```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Retrieves all the users that are banned from the guild as a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.9)") of [`BanEntry`](https://discordpy.readthedocs.io/en/master/api.html#discord.BanEntry "discord.BanEntry").
You must have the [`ban_members`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.ban_members "discord.Permissions.ban_members") permission to get this information.
would you even understand the docs? 😂
That's for one user unban. I want to unban every user in ban list
@nova summit are you using dpy or one of the forks?
Oh above one was copy one because I didn't get in docs
Retrieves all the users that are banned from the guild as a list of BanEntry.
That didn't really answer my question
did you even click the link
Does this really matters tho?
I don't really think so 👀
I could link the guide for disnake 
U serious? 😐
Would clear a majority of the doubts, so yeah
Facts, but imagine him showing not defined error on the name disnake 👀
Would be fun ngl

@client.command()
async def unbanall(ctx,member:discord.Member=None):
await bans()
await member.unban()
Like this?
Uhhhh no
Bro, bans() is a discord.Guild class method
bans = await ctx.guild.bans()
for ban in bans:
await ctx.guild.unban(ban.user)
!d discord.BanEntry
class discord.BanEntry```
A namedtuple which represents a ban returned from [`bans()`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild.bans "discord.Guild.bans").
@client.command()
async def unbanall(ctx,member:discord.Member=None):
bans = await ctx.guild.bans()
for ban in bans:
await ctx.guild.unban(ban.user)
Like this?
yes, fix the indent BTW
Thanks ❤
property created_at: datetime.datetime```
The message’s creation time in UTC.
Lemme show u
can anyone explain how can i fix this error
there are no reactions
but i added the command let me show you the code
U got intents?
!d discord.Intents.reactions
Whether guild and direct message reaction related events are enabled.
This is a shortcut to set or get both guild_reactions and dm_reactions.
This corresponds to the following events...
@maiden fable
intents bruv
how can i fix this?
in your bot constructor
ok wait
ys
intents=discord.Intents.reactions()
only problem is when i react to the message it did not show the winner
use timestamps ez
Hmm
what are those?
<t:2828828>
how to add?
!d discord.utils.format_dt
discord.utils.format_dt(dt, /, style=None)```
A helper function to format a [`datetime.datetime`](https://docs.python.org/3/library/datetime.html#datetime.datetime "(in Python v3.9)") for presentation within Discord.
This allows for a locale-independent way of presenting data using Discord specific Markdown...
requires 2.0
how do I add certain limit to snipe command?
anyone can help me?
@client.slash_command(description="Set up a mod log channel.")
async def SetModLog(ctx, Channelid: int):
async with aiosqlite.connect('channels.db') as db:
cursor = await db.cursor()
await cursor.execute("CREATE TABLE IF NOT EXISTS channels(guildid INTEGER, channelid INTEGER)")
await cursor.execute("INSERT INTO channels VALUES(?, ?)", (ctx.guild.id, Channelid))
await db.commit()
print("done")
why does it not work
im using aiosqlite
ok, so i have a sql database, i get the id from it, and i get "('828182019841327115',)" as result, but i just want to extract the id, any idea how?
this is discord py server
when i run it, it doesnt create a new table and doesnt print done
...it isn't
python discord server E
The vanity is just "dpy"
That's not what they're referring to
.
It's a tuple, so you just get the first value from it
how :V
Via index values?
??
tuple = (1, 2, 3)
variable = tuple[0] # Gives '1'```
ow ok
If you don't know how tuples work, you'll need to refer to basic Python
Go to an off-topic channel, thanks
E
@bot.command()
async def whatUser(ctx):
id = ctx.author.id
if id == 828182019841327115:
em = discord.Embed(title="players", description="players", colour=ctx.author.color)
# await ctx.send(embed=em)
l = database.length()
for i in range (int(l)):
s = database.get(i)
user = await bot.fetch_user(s)
o = user.display_name
em.add_field(name=o, value=":shrug:", inline=False)
await ctx.send(embed=em)
def length():
cur.execute("SELECT COUNT(*) FROM users_data")
s = cur.fetchone()
return s
def get(index):
cur.execute("SELECT NAME FROM users_data LIMIT 1 OFFSET ?",(index,))
n = cur.fetchone()
return n[0]
error:
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: int() argument must be a string, a bytes-like object or a real number, not 'tuple'
pls help
intents are not working for me too
a discord update broke it i think it used to work fine before they made this intent update
hi okimi
you cant int a tuple
hi
i doubt that
ok
what is thecommand to role any member using bot?
pardon?
dont you doubt me since i tried implementing intents on member_join
and member_remove
show your vars
despite importing the right intents it dosent works
yeah i doubt that show me your vars
!e
a = ("1", "2")
print(int(a))
@slate swan :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 2, in <module>
003 | TypeError: int() argument must be a string, a bytes-like object or a real number, not 'tuple'
ok
#bot-commands and thats not how you eval @pine crown
eval only executes python code lol
hi
why wouldnt it work in all servers?
@commands.has_permissions(administrator=True)
@client.slash_command(description="Set up the mod logs channel.")
async def setmodlog(ctx, modlogchannelid, YourUser: disnake.Member):
with open(f"{YourUser.guild.name}.txt", mode="a") as temp:
pass
with open(f"{YourUser.guild.name}.txt", mode="w") as file:
file.write(modlogchannelid)
embed=disnake.Embed(color=0x00d60e, title="Mod Log Channel Set", description=f"Mod log channel set to {modlogchannelid}.")
await ctx.send(embed=embed)
```would this work
try it out and indents arent correct and why are you opening the same file twice?
to create the file
the indents are correct
idk why but my file the indents are smaller
nope
in discord it looks like it only has 2 spaces for a level
which it should be 4
for each level
great
idk why my code like that
i changed to files becuase even though my db code is correct its not even working
^
so i gave up on that
did u get github copilot
there's definitely a problem if it isnt working, it cant be correct and not work
wut thats
im not
wtf
how o u not know
we were talking about it yesterday okimii
yes
¯_(ツ)_/¯
who said use it actively?
I just use it when im stuck on something
idk how to use dtabase cuz its
why would you be stuck on something
it saves time aswell
bruh ok youre trolling
dont really see a point in that lol
bruh]
weird guy
?
what about it

maybe, ill try