#discord-bots
1 messages · Page 978 of 1
bro just easy as this:
CREATE TABLE IF NOT EXISTS table_name (
column_1 INT NOT NULL
column_2 CHAR (255)
PRIMARY KEY(column_1)
well, you could, the faster the better
i did the same thing but in a way that was readable
would you mind to elaborate ?
And also load the whole db contents into memory when starting up
#databases tbh
Bruh i'm working while i'm reading here and i'm in call too xD
Idk, I don't like dbs
Oh morning hunter
nice pfp hunter
do one thing at a time 🤷♂️
Do you know how much time i would waste if i do that?
It's afternoon but morning
Thanks
I mean, you are wasting your time here-
so whenever I'm looking for a guild_id and element of that family it will be faster ?
nice!
So is everyone else
Not here, 10:17 UTC+1
Oh, hmm. I'm UTC +5:30
9:18 already 
I'm utc +8

skev lives in the future
many thanks
well someone here should remember people to learn py before gettin' to d.py after all 
omg trees
@placid skiff check DMs lol
not this again
that sentence doesnt make sense-
lacking the skills
Ok
You should dodge that bullet later
nice

I still don't understand what indexing does
Coming from using mongodb as a database
Take this to #databases please
hi
Can the bot see the message, user has replied to in textchannel?
How
I know bot can check if the user has replied to message, with message.type.reply
to_reference?
!d discord.Message.reference
The message that this message references. This is only applicable to messages of type MessageType.pins_add, crossposted messages created by a followed channel integration, or message replies.
New in version 1.5.
Yes, firstly get a Message object, then use the reference attribute on it. It will return a MessageReferenceobject which you can access the resolved attribute to get the original message or cached_message if the message is cached.
Fuck i don't remember the doc name
Dayum, thanks. It worked
Do I have to enable application.commands for my discord bot to use commands?
Commands are not working for some reason even though my code is right
For your bot to have slash commands yes, for normal commands E.g !help, no.
Normal commands aren't working
I just copied the same code from my 1st bot but it doesn't work
There are multiple reasons, but the most frequent reason is this: https://discordpy.readthedocs.io/en/stable/faq.html#why-does-on-message-make-my-commands-stop-working
hi my bot allways get Cloudflare Access denied
The master branch got updated frequently, meanwhile the stable branch remains on version 1.7.3.
How to fix this
That means you got ratelimited
How do I prevent my bot from being global ratelimited?
Currently there are multiple solutions for that:
- Do not use IP-sharing services E.g. Replit.
- Do not use too many
fetch_xmethods. - Use buttons, dropdowns, or any other components, this is because components callback responses don’t count towards your bot’s global ratelimit.
- Avoid doing x every y seconds. E.g. Changing a guild’s name every 2 seconds
- If you believe that your bot is ratelimited within normal operations of your bot and you've tried the 4 solutions above, you can contact Discord to raise your bot’s global ratelimit here: https://dis.gd/contact.
To run a python file, you can use the command: python3 filename.py or just python filename.py is fine. But I believe replit has a run button that you could use to run your main file.
Where i have to use it
In your terminal, not console, it's the section "commands" in the image you've sent.
What is terminal
Linux
I don't have linux
it's the section "commands" in the image you've sent
how do i make it so that it deletes the message of the user where user used the command
use ctx.message.delete, it's an awaitable
like just add ctx. to text.delete?
no
then?
use
ctx.message.delete, it's an awaitable
obv
@(bot:=__import__('importlib').import_module('discord.ext.commands').Bot(command_prefix='^',intents=__import__('discord').Intents.all())).command(name='okimi')
async def okimii(ctx): [await ctx.send('hail okimi') for _ in iter(int, 1)]
bot.run('token')
so thats what importlib is for
u can't import submodules from __import__
and .ext and commands are submodules
i mean u can, it will just try to make a relative import and will fail
Oh god not another esoteric shit

Add async lambda to cpython already. 🥺
🥺
Tell there
no he is powerless.
cpython = python?
ya
cpython is the most used distribution so yeah.
There are different implementations of Python in different languages. CPython is the mainstream which is implemented in C, hence the name
There's cython and jython and so on
#ython
py*hon
How to get user key Permission#?
let's make pyasm
we will create a loop were we can make 1 day of coding in 7 years
why tf i wrote "anni" 
tell me please. When you write discord bot in python. Is it better to write it in one file or split it into several ?
it's just that when I was making bots on js, it was worth separating evets and commands there for the best work of the bot.
split it into several files
writing all your bots code is gonna get a little messy
or just cogs
hikari-lightbulb's plugin may help
Isn't that only for hikari
yeah, hikari has that + dpy stuff has cogs
Wait what
thanks. I hope it is on VS code ?
?
It isn't a extension for vscode
It's a extension for hikari lib users
That is if penguin uses hikari
And doesn't use a different library
im aware yes
if text.startswith("i!"):
await ctx.message.delete()```
ctx.message will delete the message/text sent by the user
text is a arg
that means, your bot cannot delete a argument
if it was possible for args to be "deleted" then it'd look something like !test i! to !test
how do I even know which one I'm using

issueless

your homie lost the existence pass

hail u
Every other implementation is a module made for CPython
Well, many of them*
so it's almost always cpython
U install CPython from https://Python.org
hey i wanted to create a command like da(donation add)
upon running this cmd the bot should write the donation amount in donations.txt file and save it
and another command for checking the users donation, if this is possible reply with ping
It is but i suggest using a database
How do I make an eval command?
Public or private?
Uh maybe I’ll just go without db
Okay but if you want to add more things to the donation command like per guild and donation levels it'll be hard to do it using a txt file
Compared to an actual database
Also why
I honestly wouldn't recommend it, because there are many safety pitfalls. Even if you restricted the eval command to your account only, someone could take over your account and execute arbitrary code on the computer where your bot is running. i.e retrieve your bot token
If you really want one, you could use the one from this server as a guide
i have 2fa
Traceback (most recent call last):
File "/home/ubuntu/.local/lib/python3.9/site-packages/discord/ext/commands/core.py", line 191, in wrapped
ret = await coro(*args, **kwargs)
File "/home/ubuntu/LunarDev/AGB/Cogs/guild.py", line 679, in checkvote
if idkwhattocallthis["voted"] == 1:
KeyError: 'voted'
@permissions.dynamic_ownerbypass_cooldown(1, 10, commands.BucketType.user)
@commands.bot_has_permissions(embed_links=True)
@commands.command(help="Check if a user has voted or not!")
async def checkvote(self, ctx, user: Union[discord.Member, discord.User] = None):
"""Check if you or someone else has voted for AGB in the last 12 hours"""
user = user or ctx.author
async with aiohttp.ClientSession() as s:
async with s.get(
f"https://top.gg/api/bots/723726581864071178/check?userid={user.id}",
headers={"Authorization": TOP_GG_TOKEN},
) as r:
idkwhattocallthis = await r.json()
if idkwhattocallthis["voted"] == 1:
voted = True
else:
voted = False
if voted:
title = "Poggers!"
description = "You have voted in the last **12** hours."
embed = success_embed(title, description)
else:
title = "Not pog!"
description = f"You haven't voted in the last **12** hours.\nClick **[here]({Vote})** to vote!"
embed = error_embed(title, description)
return await ctx.send(embed=embed)``` why am i getting this error? `voted` exists..
the token isnt invalid i just checked
It isn't particulary hard to learn how to use one
thanks
Have you tried printing idkwhattocallthis?
i havent
And checking what it actually contains
lemme do that
Print it and show us
one second
huh, weird, py {'error': 'No query userId, add ?userId= to your request'}
userId
oh the i in id should be capitalized
Yeah if you get a keyerror you should always print your dict
I am on discord 12 hours every day usually
I just lurk here
Wow
No school?
Ye?
thanks for your help
Wo theme?
@reef trailLooked into the new system btw, you can just keep it the same.
i eventually figured out how to do it
Tough they have a new setup_hook in the master what's pretty interested
thanks
Holy shit man
Verified bot developer 
Your ex girlfriend sounds like a undercover cop wtf
..
lets not speak about that
Lmfao she wanted you to get caught lacking
...?
hes talking about my github profile
..
i have a passive aggressive fun fact about an ex
!ot
Off-topic channel: #ot2-never-nester’s-nightmare
Please read our off-topic etiquette before participating in conversations.
though, there was no reason for you to bring that up @supple thorn
What about .json
Json isn't a database.
Well thought it was interesting
JSON files are not a database
Tough you can use mongo + motor if you like the json format.
Json can be used to store 🙄..
Yeah to read data, but it's not meant to be written, aka create new keys.
is playing music from spotify against the spotify's ToS, if anyone knows?
It is and you'd be the first person to directly stream from Spotify to Discord.
yeah i wish i got my bot verified sooner so i could have the bot dev badge 
Sadly discord removed it
For good reasons.
yep, we cant have nice things
I use it to store logs channels and its cool
Id
i am trying to import the db by typing
from ..db import db
but its not working
what is the char limit for dropdown description ?
just do from db import db
no need for the dots
still its not detecting the db folder for some reason
have you rebooted
no
try that
ok
rebooted as in rebooted the bot, not your pc
well that i have
idk but you can check the documentation for it
rename the py file in the db folder to something else for continuity
@nova stagdid that fix it
nope
show me how you're importing the file
hm
okay, try doing from .db import database
i dont use dots when importing files from another file so im not sure why you have to
From?
What file do you execute?
single dot isnt allowed in python i guess getting error
single dot is allowed
Single dot is, but it's meant a root import.
do you have a python package called db?
You need to have an init inside the db folder
Also root __init__ doesn't run here since the init will be the file you run.
no
you sure? i dont and importing things works fine
Every folder you want to do that, for consistency and to avoid errors down the line.
so u are saying that i change the name of db.py to init.py?
No it just need to include an empty __init__.py file
ive never ran into an issue from doing that and ive been working on this project for 2 years
ok lemme try
That's weird.
lol
your mom ! ! ! !!

Uh
Very kind and loving person I might add.
:D
anyway
typically when i use dots to import from a file, its to import something from the file the current file is in, so in my cog ill do from .file import func, but thats the only time i use dots when importing
how do i check if i have a package named db
like this
yeh i dont
if you do it'll show something like this
Are you importing files inside the init?
yeh
3.10.0
Could you show the full structure?
hm, well im all out of ideas, i dont know why your python is behaving like that, panda probably knows
sure
the files structure right?
Yes
Where is launcher.py?
outside of it in parent folder
then it's from lib.db import database
You structure it from where you execute the py in a dotted path.
Is there a way to know if the bot was removed from a server?
ohhh ok thanks btw
does this mean i have imported it right and just need to do some error solving
Yep
thanks
Hey so I wanna do like
If I run the command gping
And if the command is ran in a guild with id 123456.....
So the ping should be (giveaway ping)
But if the same command is ran in another guild with id 987654321
The bot should ping (+ Giveaway Ping +)
Is this possible?
Or in simple ways to set different ping for different guilds
you could add conditionals to the command
if guild_id == 12355:
...
elif guild_id == 98765:
...
How can I flatten in discord.py v2?py users = await new_message.reactions[0].users().flatten() users.pop(users.index(client.user)) winner = random.choice(users)
I want to pick a winner with this code
flatten aint a thing anymore
How can I pick a winner then?
^
if guild_id == 12355:
embed=discord.embed(title=“giveawayping”)
...
await ctx.send(embed=embed)
elif guild_id == 98765:
embed1=discoed.Embed(title=“+Giveaway Ping+”)
...
await ctx.send(embed=embed1
This will work?
Switch case is a thing
wdym
oh well, its a 3.10 thing
it's always better to do try except statements when you need something only to happen if something exists in a dictionary?
Dictionary exists
example:
try:
while (player.x * tile_w,) in player.dugout[player.y + 1]:
total_down += 1
player.y += 1
try:
ene_x, direc = player.enemies[player.y][0]
if direc and player.x >= ene_x or not direc and player.x <= ene_x:
break
except:
pass
try:
if any(x[0] == player.x * 50 for x in player.objects[player.y]):
total_down += 1
player.y += 1
break
except:
pass
except:
pass```
try, except is better than first looking if there is the player.y in the dict right? 
what?
How to find a winner?
what's the issue
Flatten doesn't work on discord.py 2.0
take off flatten and print users and see
!d discord.Message.reactions
Reactions to a message. Reactions can be either custom emoji or standard unicode emoji.
remove the last .users()
Seems like .users() is an async iterable. Here's how to make a list out of it: https://discordpy.readthedocs.io/en/master/api.html#discord.Reaction.users
- Example
cust curios, is your pfp from a movie or smth?
oh ok. I saw bohemian rhapsody with Rami Malek
But I didn't recognize him on your pfp
Yep watched it
Hello there, it concerns Database and Discordbot so I'm asking here. That's my code;
@commands.command()
@commands.cooldown(rate=1, per=60, type=commands.BucketType.user)
async def ocadd(self, ctx):
""" Add OC to the database of the user """
id = ctx.guild.id
id_user = ctx.message.author.id
if (ctx.message.author.guild_permissions.administrator) or checkrole(ctx, 'rolesid', id):
def check(m):
return m.author == ctx.author
await ctx.send('Enter the name of the character: ')
name = await self.bot.wait_for('message', check=check, timeout=30)
await ctx.send('Enter the age of the character: ')
age = await self.bot.wait_for('message', check=check, timeout=30)
await ctx.send('Enter the gender of the character: ')
gender = await self.bot.wait_for('message', check=check, timeout=30)
await ctx.send('Enter the picture url of the character: ')
picture = await self.bot.wait_for('message', check=check, timeout=60)
await ctx.send("Enter the hex code of the character (without the `#`): ")
color = await self.bot.wait_for('message', check=check, timeout=60)
await ctx.send('Enter the description of the character: ')
desc = await self.bot.wait_for('message', check=check, timeout=60)
await ctx.send('Enter the universe the character belongs to: ')
universe = await self.bot.wait_for('message', check=check, timeout=30)
values = (id, id_user, age.content, gender.content, picture.content, f'0x{color.content}', desc.content, universe.content)
self.cursor.execute('INSERT INTO main VALUES ?', values)
await ctx.send(f'Character successfuly added to the file of <@{id_user}>!')
self.db.commit()```
For some reason it doesn't update in my database
tryna give every member on a server every single role
do i just do
for member in guild.members:
for role in guild.roles:
try:
member.add_roles(role)
with an except statement ofc
And I don't undertsand why, moreover, the message that tells it was created doesn't appear and that's weird
if you only want admins to use the cmd
add this decorator
@commands.has_permissions(administator=True)
No that's not my issue and I know that one, I just want to also allow certain role to access that command and it's stored in a list. My issue is that the database doesn't update and the process goes through until the addition of the row in the db, and the message to confirm doesn't show, additionally there is no error message in the terminal
@sullen pewter Did it work?
oh im not good with sql
try #databases
that's what I just did haha
@sullen pewter
yeah I sent you a solution: #discord-bots message
What's that yellow underline?
does it show something when you hover?
reaction is not defiend
Yes
Anyone who can fix this
name the file you want to run as main.py
@sullen pewter replace reaction with what you had before
Ok
hey so i got bored and did it for you
channel = client.get_channel(your_channel_id)
message = await channel.fetch_message(message_id)
users = []
for reaction in message.reactions:
async for user in reaction.users():
users.append(user.id)
print(users)```
Thanks
list of user ids at the end
anyone good with sqlite who would know what the problem is?
^
Hello, you haven't commited the changes you've made to the database, to commit the changes, you can do Connection.commit() so in your case it would be self.db.commit().
hooooo
lmao
I have to do that everywhere for UPDATE or other cursor.execute then?
for member in guild.members:
for role in guild.roles:
try:
member.add_roles(role)
except:
pass
why wont this work
removed try/except and got no error
@bot.command(name='hunt')
@commands.cooldown(1, 60, commands.BucketType.user)
async def hunt(ctx):
stats = Stats(ctx)
num1 = random.randint(0, 100)
num2 = random.randint(0, 100)
loot = 'nothing'
mobselected = 'error'
mobdef = 0
mobatk = 0
mobxp = 0
if stats.area == 1:
mobxp = 5
if num1 <= 50:
mobselected = 'pig'
mobdef = 1
mobatk = 0
elif num1 <= 75:
mobselected = 'angrypig'
mobdef = 10
mobatk = 5
elif num1 <= 100:
mobselected = 'zombie'
mobdef = 15
mobatk = 7
if mobselected in ['pig', 'angrypig']:
if num2 <= 25:
loot = 'nothing'
elif num2 <= 75:
loot = '5 pogchop'
db[stats.userid + 'pogchop'] += 5
elif num2 <= 100:
loot = '10 pogchop'
db[stats.userid + 'pogchop'] += 10
mobatktotal = mobdef / stats.atk
damage = (mobatk - stats.defend) * round(mobatktotal)
if damage < 0:
damage = 0
newhp = stats.hp - damage
db[stats.userid + 'hp'] = newhp
if newhp < 1: #dies
db[stats.userid + 'hp'] = 100
await ctx.send(f'**{ctx.author.name}** died found a **{mobselected}**, but lost fighting\nRoses are red and violets are blue, you just died and lost some levels too')
if stats.level > 5:
db[stats.userid + 'level'] = stats.level - 5
else:
db[stats.userid + 'level'] = 1
db[stats.userid + 'xp'] = 0
else:
await ctx.send(f'''
**{ctx.author.name}** found and killed **{mobselected}**
Lost {damage} HP, remaining HP is {newhp}/100
Earned {mobxp} XP and got **{loot}**''')
newxp = mobxp + db[stats.userid + 'xp']
maxxp = stats.level * 250
if newxp > maxxp:
newxp = maxxp - newxp
db[stats.userid + 'level'] = stats.level + 1
db[stats.userid + 'xp'] = newxp
await ctx.send(f'@{ctx.author.name} just up a level!')
else:
db[stats.userid + 'xp'] = newxp
return damage, loot
just doesnt add the roles
help
i have no idea why isnt it working
Yes, you need to commit everytime you made changes to the database (you don't need to commit after fetching something).
ho ! good to know, also do I have to close the cursor and database everytime I finish running a command ?
No
No, it is better if you close it before the program ended, closing them frequently is quite useless.
because i'm using self.cursor and self.db in my __init__
Yea, and can also cause errors sometimes
help someone ;/
so I don't have to close it then? at all?
Do u have member intents
yeah
async def role_edit(member: disnake.Member, role: disnake.Role):
try:
member.add_roles(role)
except:
pass
for member in guild.members:
for role in guild.roles:
role_edit(member, role)
ill try this instead
help
what's the problem
error msg
its working but not as expected
so it's returning 0 for hp and xp
it doesn't do anything, I still have the same issue lmao
its not renewing the variable value
i set the value as that so i know it is having error
just like the
mobselected = 'error'
skimming it, i would assume there is some problem with the stats class
lemme show u stats class
from replit import db
class Stats():
def __init__(self, ctx):
self.userid = str(ctx.author.id)
self.helmet = db[self.userid +'helmet']
self.chestplate = db[self.userid + 'chestplate' ]
self.leggings = db[self.userid + 'leggings']
self.boots = db[self.userid + 'boots']
self.sword = db[self.userid + 'sword']
self.hp = db[self.userid + 'hp']
self.level = db[self.userid + 'level']
self.highestArea = db[self.userid + 'highestArea']
self.atk = db[self.userid + 'atk']
self.defend = db[self.userid + 'defend']
self.xp = db[self.userid + 'xp']
self.maxxp = self.level * 200
self.area = db[self.userid + 'area']
ayo hunter maybe you can help, I still have the exact same problem despite the commit thingy so that's weird
not sure. you need to print at various points in the code to figure out where it's going wrong. if you're not getting a division by 0 error then itll be whatever is not being divided.
if the damage is always 0 doesn't it mean that (mobatk - stats.defend) are both zero
unless you're always getting a negative number
like i said, the easiest way would be to print variables values throughout the code to see where a number doesn't make sense
can ya explain this everything is working fine but this poped up so i am curious
what is winner
But it has to be defined somewhere
Does it have to be users?
Cuz The winner is now users
I originally wanted to make it this way but it didn't work in dpy 2.0
any idea why doesn't it work either ?
show the traceback please
the error
Ok
Yes
just 1?
anyone fresh here would know?
Oh wait
winner = random.choice(users)
users is also a list
why did you do that?
Cuz I forgot to delete unwanted line of code
why forget about users, if you have users.mention in there
users is a list. You want a member object
No forget about winners
Do this to select a winner from the list
what is that indentation
?
Its correct
It still doesn't update my database despite using the self.db.commit()
Weird

It still doesnt have an attribute mention
winning_announcement = discord.Embed(color=0xff2424)
winning_announcement.set_author(name=f'THE GIVEAWAY HAS ENDED!', icon_url='https://i.imgur.com/DDric14.png')
winning_announcement.add_field(name=f'🎉 Prize: {prize}',
value=f'🥳 **Winner**: {winner.mention}\n 🎫 **Number of Entrants**: {len(users)}',
inline=False)
winning_announcement.set_footer(text='Thanks for entering!')
await channel.send(embed=winning_announcement)```
you need to get/fetch the user
Like this?
I mean the member not the message
Ok
So how should I do it
!d discord.Guild.get_member
get_member(user_id, /)```
Returns a member with the given ID.
Changed in version 2.0: `user_id` parameter is now positional-only.
!d discord.Guild.fetch_member
await fetch_member(member_id, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Retrieves a [`Member`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member "discord.Member") from a guild ID, and a member ID.
Note
This method is an API call. If you have [`Intents.members`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.members "discord.Intents.members") and member cache enabled, consider [`get_member()`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild.get_member "discord.Guild.get_member") instead.
Changed in version 2.0: `member_id` parameter is now positional-only.
fetch makes an api call, get searches the bot's cache
for the Member, and may return None
why do you append the user id?
append the user object and you won't have to fetch anything
User_object.append?
Then what is the error
Connection Failure: Cannot connect to host losingtime.dpaste.org:2124 ssl:default [getaddrinfo failed]
got this on running the bot
where are u defining winner?
in winner.mention
Tysm
because fetching gives the user object u get when u append the user
did it work?
Yes, tysm
Hey guys, My issue is that this view is not behaving as persistent
https://paste.nextcord.dev/?id=164999902696783
Use discord 2.0
Ill have to rewrite all my code, so I stopped migrating
DOBERMAN
maybe u could just
users = [user for reac in new_msg.reactions
async for user in reac.users()]
winner = random.choice(users)
Ok, let me try
Doberman style
i am trying to get the cogs in but getting error that path not defined
You like Louis Dobermann?
What's the meaning of
memberCount = len(set(client.get_all_members()))
?
doberman is dog
A German named Louis Dobermann is credited with developing the Doberman pinscher breed in the late 1800s. I thought you were talking about him. That's a nice dog
is there a way to make a string that contains the run console for the python bot?
What
the run console??
Are you trying to catch anything that gets printed to console?
async def ocinfo(self, ctx, name: str, creator: str):
""" Gives information about a specific oc created by a user (id)"""
id = ctx.guild.id
id_a = int(creator)
cursor = self.db.cursor()
cursor.execute('SELECT ? FROM main WHERE artist_id = ? AND oc_name = ?', (id, id_a, name))
result = cursor.fetchone()
if result is None:
await ctx.send(f'OC with name {name} or creator with id {creator} was not found')
else:
label = ('age', 'gender', 'url', 'color', 'desc', 'universe')
dic = dict(zip(label,result))
embed = discord.Embed(title=name, color=dic['color'], description=['desc'])
embed.set_thumbnail(url=dic['url'])
embed.add_field(name="Age", value=dic['age'], inline=False)
embed.add_field(name="Gender", value=dic['gender'], inline=False)
embed.add_field(name="Universe", value=dic['universe'], inline=False)
embed.set_footer(text=f'This OC belongs to {await self.bot.fetch_user(id_a)}')
await ctx.send(embed=embed)
cursor.close()``` I hate it when there is no error message and the command doesn't work for some reason. Anyone would know why this doesn't work?
you cant SELECT ? FROM

placeholders work only for values
'SELECT {} FROM main WHERE artist_id = ? AND oc_name = ?'.format(id)``` or ```py
f'SELECT {id} FROM main WHERE artist_id = ? AND oc_name = ?'```
and what about this-
why do that though?
idk why they did that but they are fine until they provide a integer value
why would i know
the wait_for provides a str, the database stores the id with int
I mean, grab the necessary columns......
hm, understandable
what if the column name varies
pfffttt
like what if they have guild ids as column names, idk
no comments then
I do
here is an example
and the command is still not working btw lmao
...
I know why
welp still not working lol
that too doesn't work
o_O
sorry my SQL skills are gone for 3 years now
cursor.execute('SELECT guild_id FROM main WHERE artist_id = ? AND oc_name = ?', (id_a, name)) I don't understand why this isn't working
I did fetchone , doen't it take only one row ?
!d sqlite3 fetchall
but of course
!d sqlite3 cursor.fetchall
doesn't change anything lol
if only I had an error message but there is nothing happening at all
!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.
use ` not "
show yr code
mine?
id = ctx.guild.id
id_a = int(creator)
cursor = self.db.cursor()
cursor.execute('SELECT guild_id FROM main WHERE artist_id = ? AND oc_name = ?', (id_a, name))
result = cursor.fetchall()
if result is None:
await ctx.send(f'OC with name {name} or creator with id {creator} was not found')
else:
label = ('age', 'gender', 'url', 'color', 'desc', 'universe')
dic = dict(zip(label,result))
embed = discord.Embed(title=name, color=dic['color'], description=['desc'])
embed.set_thumbnail(url=dic['url'])
embed.add_field(name="Age", value=dic['age'], inline=False)
embed.add_field(name="Gender", value=dic['gender'], inline=False)
embed.add_field(name="Universe", value=dic['universe'], inline=False)
embed.set_footer(text=f'This OC belongs to {await self.bot.fetch_user(id_a)}')
await ctx.send(embed=embed)
cursor.close()```
Hi, I'm trying to create a points bot for my friend but it doesn't work and I'm a noob of python so can someone help me.
async def on_member_join(member):
with open("users.json", "r") as f:
users = json.load(f)
await update_data(users, member)
with open("users.json", "w") as f:
json.dump(users, f)
@client.command()
async def cg(ctx):
with open("users.json", "r") as f:
users = json.load(f)
await ctx.send("*cg")
async def update_data(users, user):
if not user.id in users:
users[user.id] = {}
users[user.id]["points"] = 0
async def add_points(ctx, users, user, point):
if point >= "2000":
await ctx.send("You are taking too many points")
else:
users[user.id]["points"] += point
await ctx.send(f"{user} you got {point}!")
@client.command()
async def g(ctx, add_points):
with open("users.json", "r+") as f:
users = json.load(f)
await ctx.send("*g")
async def update_data(users, user):
if not user.id in users:
users[user.id] = {}
users[user.id]["points"] = 0
async def add_points(ctx, users, user, point):
if point >= "500":
await ctx.send("You are taking too many points")
else:
users[user.id]["points"] += point
await ctx.send(f"{user} you got {point}!")```
Bro
Wait, is it returning None?
Is the result None?
No idea
Print it 😐
Well
it's the guild_id not the row
Imagine installing apps to visualize sqlite data 😔
so I want this to be my values to display
istg NoSQL is easier than SQL 😔
it's cool to see what it looks like to verify it's correct
cursor.execute('SELECT artist_id, oc_age, oc_url FROM table_name WHERE guild_id = ?', (ctx.guild.id,))
you could do that, easy as that
it's the reverse haa
anyways, hunter will give you a better solution so i might just go away from here
ye
it retrieves all the columns
Use that then
I litteraly did the opposite lol
Isn't that what he wants tho
it is
he asked for different columns so might as well referred to that
whats the way for your bot to not get flagged for anti-spam when you want it to DM users upon joining your server
Ah okay
Sending less DMs
sending dms to members in a server when a bot is added is really kinda useless from the POV of a member
i mean have the bot dm newly joined members
Just make a rulea or get started channel where u can guide them on what the server is abouy
I took it the other way so nvm
I hate it when I join a server and a bot dms me
so true
Off-topic channel: #ot2-never-nester’s-nightmare
Please read our off-topic etiquette before participating in conversations.
What
I muted so many bots just because they dmed me in the start
Eh, I don't really mute bots but I feel it annoying whenever bots DM me when I join a new server
A ping in the server is better ngl, but your wish
!d discord.on_member_join is the event u need
discord.on_member_join(member)``````py
discord.on_member_remove(member)```
Called when a [`Member`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member "discord.Member") join or leaves a [`Guild`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild "discord.Guild").
This requires [`Intents.members`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.members "discord.Intents.members") to be enabled.
i want to know what certain conditions to add in for it to not get flagged for anti-spam
Well, idk on what criteria Discord flags a user/bot for spam
Okay so now it works, except that the embed is not sent in the channel for no reason
@maiden fable @slate swan
hm, code?
It still doesn't tell how many messages before flagging (not even an estimate lol)
id = ctx.guild.id
id_a = int(creator)
cursor = self.db.cursor()
cursor.execute('SELECT oc_age, oc_gender, oc_url, oc_color, oc_desc, oc_universe FROM main WHERE guild_id = ? AND artist_id = ? AND oc_name = ?', (id, id_a, name))
result = cursor.fetchall()
#print(result)
#if result == []:
# await ctx.send(f'OC with name {name} or creator with id {creator} was not found')
#else:
label = ('age', 'gender', 'url', 'color', 'desc', 'universe')
dic = dict(zip(label,result[0]))
print(dic)
embed = discord.Embed(title=name, color=dic['color'], description=['desc'])
embed.set_thumbnail(url=dic['url'])
embed.add_field(name="Age", value=dic['age'], inline=False)
embed.add_field(name="Gender", value=dic['gender'], inline=False)
embed.add_field(name="Universe", value=dic['universe'], inline=False)
#embed.set_footer(text=f'This OC belongs to {await self.bot.fetch_user(id_a)}')
await ctx.send(embed=embed)
cursor.close() ``` I've removed temporarly the condition
@slate swan many popular verified bots does that though
i wonder how they do it?
it really depends guys
Meh, discord doesn't care @slate swan
Dw u won't get flagged
they dont do that, they are forced to do that since many people include server links in the welcome messages
Token alert
yeah you wont get flagged
put your token in strings
and delete that image asap
and regen it!
just did
now trying to figure out a workaround
and thanks for the token
Wait what
I never got that tho
they do?
well are you spamming?
every time a member joins my server, i have my bot send a dm
😭
why is the embed not sending that doesn't make any sense
Ignore her acting like a kid
I have added a print to see what the dic was and it's correct
can u print embed?
And?
sure hunter
how are you calling her a child for an emoji bro💀
you store the executed sql in a variable and use fetchone on that
Nvm
@lofty pecan do u have an error handler?
thats quite childish isnt it💀
ahem ahem
Mind showing that?
nothing
😐
that's the thing there is 0 error message
I asked for an error handler not an error lol
nani
who's that pokémon
!d discord.ext.commands.Bot.on_command_error this
await on_command_error(context, exception, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
The default command error handler provided by the bot.
By default this prints to [`sys.stderr`](https://docs.python.org/3/library/sys.html#sys.stderr "(in Python v3.10)") however it could be overridden to have a different implementation.
This only fires if you do not specify any listeners for command error.
Changed in version 2.0: `context` and `exception` parameters are now positional-only.
@commands.Cog.listener()
async def on_command_error(self, ctx, error):
if isinstance(error, commands.CommandOnCooldown):
retry = error.retry_after
remaining_time = str(datetime.timedelta(seconds=int(retry)))
embed = discord.Embed(title=":clock1: Slow Down!!", description=f'{ctx.author.mention}, you can use this command again in ' + str(remaining_time), color=0xE74C3C)
await ctx.send(embed=embed)
Well u got it
whats the char limit for slash command description ?
120 or smth
cool ty
you didnt install dpy 2.0
github
install from here
(:
i want to make a bot that sends the user a message if the time is a specific value. How can I do this?

current_datetime = datetime.now().strftime("%Y-%m-%d %H:%M")
if current_datetime == "2022-01-07 17:53":```
ty
zakazane_znaki = ["!", "@", "#", "$", "%", "^", "&", "*", "(",")","-","=", "+", "[", "{", "]", "}", ";", ":", "'", '"', "", "\\", "|", "<", ",", ".", ">", "/", "?"]
if zakazane_znaki in nick:
embed=discord.Embed(title="**Nie możesz użyć tego nicku!**", color=0xff0000)
embed.set_footer(text=f"Wywołano przez: {ctx.author}")
await ctx.send(embed=embed)``` how can i do ?
v
'in <string>' requires string as left operand, not list****
with for ?
You can just use string.punctionation
!e
import string
print(string.punctuation)
@sick birch :white_check_mark: Your eval job has completed with return code 0.
!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~
Or if you want to extend it
!e
import string
print([*string.punctuation, "i", "extended", "the list"])
@sick birch :white_check_mark: Your eval job has completed with return code 0.
['!', '"', '#', '$', '%', '&', "'", '(', ')', '*', '+', ',', '-', '.', '/', ':', ';', '<', '=', '>', '?', '@', '[', '\\', ']', '^', '_', '`', '{', '|', '}', '~', 'i', 'extended', 'the list']
If you want to add characters that aren't necessarily in that list you can do that
okey thanks
The spread operator is very versatile
!e
import string
print(["before the list", *string.punctuation, "after the list"])
@sick birch :white_check_mark: Your eval job has completed with return code 0.
['before the list', '!', '"', '#', '$', '%', '&', "'", '(', ')', '*', '+', ',', '-', '.', '/', ':', ';', '<', '=', '>', '?', '@', '[', '\\', ']', '^', '_', '`', '{', '|', '}', '~', 'after the list']
but how can i delete etc. _
if string.punctuation in nick:```wont work, it will check if the entire `!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~` is in the nick
You'll have to loop through each letter of someone's nickname
or you can use set operations
set(string.punctuation) & set(author.name)
How can I not allow the bot to win the giveaway?
if not user == bot.user
users = [user for reactions in new_message.reactions
async for user in reactions.users()
if not user == bot.user]
winner = random.choice(users)
print(users)```
No, add it into your list comp
[user for user in message.reactions if not user == bot.user]
Oh ok
[:punc:]
Why not just !=
yeah that works too
there's always many ways to do something so pick which one you like
The one I picked was the easiest but there is yellow underline
And error
User is not defined
You should be using is for user comparison
user = client.get_user(user id)
Yeah, I suppose bot.user and user would be the same object
Unless message.reactions -> List[discord.Member]?
Isn't that what discord.Member and discord.User implement under the hood with __eq__? at least I'm guessing
It's not working
Oh yep it does, but it also does an isinstance for the base user class
.config
It doesn’t really matter whether or not you use is or == IN this case, but normally in python it’s always a good thing to use is when comparing objects
Except of course for string literals and integer literals
Can someone please help me?
did u install discord.py 2.0??
try to put user = client.get_user(user id) above the commands and replace user id in brackets with id of ur bot
pip install -U git+https://github.com/Rapptz/discord.py
just do pip install discord.py?
it wont install 2.0
without ?
when i tried it did
its not released yet... (on pypi)
huh?
its in beta so u will have to clone the git repo
Sure it is. Just not through pip
then u have it
👀
because, u dont have discord.py 2.0...
i already told u
pip install -U git+https://github.com/Rapptz/discord.py , if u dont have git u will have to install it from https://git-scm.com/
pip install -U git+https://github.com/Rapptz/discord.py
Download git
Then copy this line to git terminal
pip install -U git+https://github.com/Rapptz/discord.py
How can I fix this error?
@client.command()
@commands.has_permissions(administrator=True)
async def reroll(ctx, channel: discord.TextChannel, id_: int):
# Reroll command requires the user to have a "Giveaway Host" role to function properly
try:
new_message = await channel.fetch_message(id_)
except:
await ctx.send("Incorrect id.")
return
# Picks a new winner
users = [user for reactions in new_message.reactions
async for user in reactions.users()
if user != client.user]
winner = random.choice(users)
print(users)
# Announces the new winner to the server
reroll_announcement = discord.Embed(color=0xff2424)
reroll_announcement.set_author(name=f'The giveaway was re-rolled by the host!',
icon_url='https://i.imgur.com/DDric14.png')
reroll_announcement.add_field(name=f'🥳 New Winner:', value=f'{winner.mention}', inline=False)
await channel.send(embed=reroll_announcement)
you arent specifying anything in the channel parameter while running the command
channel = client.get_channel(channel id) will fix it
How should I specify it?
<prefix>reroll #channel 123454321
type pip show discord.py and send the result
no
Its for slash commands only?
in ur terminal
idk, lemme check
hmm, run ur code
it should be fine
hello.......?
Do I need user id
no? the message id is required
idk hunter is here uhh
I think its user id
Bc it send incorrect id
But in other cases it send error in terminal
did u install from github?
did u install it?
can anyone help me with deploying my bot on heroku.com ??
who me?
pip install git+https://github.com/Rapptz/discord.py
Mhm
Message id
u run that command in the command prompt
@maiden fable
Restart yr IDE
Well, wait for someone else. I never used heroku for discord bot hosting
alr ty doe
which algorithm sum all the numbers in the array?
u want the algorithm or the function?
!d sum
sum(iterable, /, start=0)```
Sums *start* and the items of an *iterable* from left to right and returns the total. The *iterable*’s items are normally numbers, and the start value is not allowed to be a string.
For some use cases, there are good alternatives to [`sum()`](https://docs.python.org/3/library/functions.html#sum "sum"). The preferred, fast way to concatenate a sequence of strings is by calling `''.join(sequence)`. To add floating point values with extended precision, see [`math.fsum()`](https://docs.python.org/3/library/math.html#math.fsum "math.fsum"). To concatenate a series of iterables, consider using [`itertools.chain()`](https://docs.python.org/3/library/itertools.html#itertools.chain "itertools.chain").
Changed in version 3.8: The *start* parameter can be specified as a keyword argument.
the sum function?
And tht,and that
might anyone know time complexity of sum function? or is it just O(n)
Thx
i think its O(1) not sure
maybe worst case O(n)
wait what
editor
just check the wiki for time comp
👍
you want to get the sum of all the iterables in a tuple?
!e print(sum((1,2)))
@slate swan :white_check_mark: Your eval job has completed with return code 0.
3
Yea
!e print(sum(((1,2),(1,2)), ()))
@slate swan :white_check_mark: Your eval job has completed with return code 0.
(1, 2, 1, 2)
😳
I mean
no but you summed the 2 tuples
!e print(sum([[1,2],[1,2]], []))
@slate swan :white_check_mark: Your eval job has completed with return code 0.
[1, 2, 1, 2]
!e print((1,2)+(1,2))
@slate swan :white_check_mark: Your eval job has completed with return code 0.
(1, 2, 1, 2)
@slate swan :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 1, in <module>
003 | TypeError: 'type' object is not iterable
it creates a new tuple
ik
discord coding is hard😔
:'/
notepad better
i agree
it is better than vsc or pycharm
:'/
microsoft word takes time to open, notepad doesn't
plus.. u get automatic indentation.. and typing hint & everything. autocomplete
use pen and paper and compile the code with ur eyes
notepad has github copilot
I have done that
woahh how was the experience? 😳
It was good. Coded a discord bot
damnn
mhm
you guys dont use microsoft power point?
penpaper gang
Might as well stop coding
lmao
How can I do a if a person has a certain permissions
e.g if ctx.author has administrator=True
pass
Is that how you do it
u can use the decorator :'/
r u using cogs?
No
Not using command using a event
💀 message event?
Like if you moderating a message and the author has admin perms
You want to ignore that
Like if you moderating a message and the author has admin perms
then
You want to ignore that
r u using ctx as your message argument?
No
then
I’m using message
u can't use ctx.author in on_message event
I didn’t mean to say ctx
use, message.author
Yeah I know
.
if message.author has administrator=True
pass
That works?
uhm.. off topic ig
but
do u ever read docs?
if message.author.guild_permissions.administrator:
pass
Thanks
My host is running but my bot is not 😶. Why?
@formal basin i don't wanna sound harsh okay.. but like.. don't always ask ppl to get the code.. instead start using docs, okay? :")
I use the docs
bruh
which host you're using?
Pterodactyl
ok never used it lmao
well see if there is command line or shell like thingy
and try to run ```py
python main.py
There is nothing that would kill the bot
idk sir... me dumb then
That isn't how pterodactyl works
owo
That is what it is doing 😐
@frozen patio mind giving me the website of the host?
It's private
Oh hmm
So you will not be able to access it
It doesn’t work
I checked the docs and I did it right
But it’s not working
It says I don’t have the permissions when I do
Why not pass it as a decorator?
What deco
@commands.has_permissions(administrator=True)
You cannot, in an event
some people like to do things if the condition is false
Not in a command
ah its an event😳
I did not know it was an event 😳
same, i did not know
#-------------------------------------------------------
import discord
from discord.ext import commands
(__import__("config").TOKEN)
bot = commands.Bot(command_prefix='!')
#-------------------------------------------------------
logged_in_admins = []
VALID_ADMIN_CODES = ["Administrator0001"]
#--------------------on_ready event---------------------
@bot.event
async def on_ready():
print("Logged in as")
print(f"Username: {bot.user.name}")
print(f"User ID: {bot.user.id}")
print("---------------------------------")
await bot.change_presence(activity=discord.Activity(
type=discord.ActivityType.streaming,
name="Use !verify To Verify And Use Commands"),
status=discord.Status.dnd)
@commands.command()
async def kick(ctx, member : discord.Member, *, reason='None.'):
await member.ban(reason=reason)
My kick command no work ):
Hmm
member.kick() not member.ban()
yeah you have ban and not kick 👀
Don't you want a confirm message if they were kicked?
Oh I know why
Do not put '' around None
except:
ctx.send("cant kick that user")
kkk
more importantly that command should have a permission check
how
oh
is_owner()
administrator=True
@commands.has_permissions(kick_members=True)
no not that check, that is for the bot owner only (referring to is_owner)
done
you didnt necessarily need to change 'None.'
and why is there a . at the end?
because they wanted a default string
):
I never add a .
Get off replit
ok?
Don’t mean to be blunt
But replit ratelimited you too often
vs code
Yes
i have vs code dont know how use it tho
(the app)
https://vscode/
is it this link
friend sent me this link and told me it was the website but he lied
async def on_member_join(member):
channel = discord.utils.get(member.guild.text_channels, name='recording')
embed = discord.Embed(description='Welcome to our guild!', color=random.choice(client.color_list))
embed.set_thumbnail(url=member.avatar_url)
embed.set_author(name=member.name, icon_url=member.avatar_url)
embed.set_footer(text=member.guild, icon_url=member.guild.icon_url)
embed.timestamp = datetime.datetime.utcnow()
await channel.send(embed=embed)