#discord-bots
1 messages ยท Page 752 of 1
agreed
also uh, my intellisense on vs code is not working, is there a fix for that
for example
if member == None:
member = ctx.author```
is basically
`member = member or ctx.author`
Send your code and question here
there's no intellisense for this lib ๐ค
wait what, it did before
maybe small bits, not all
it had for it, but it doesn't work for me
Actually u counted them correct
What if the member has only one role? Then the roles variable will be an empty list
yeah, thought it was zero based ๐ค
if they only have one role, then it still shows
Cz it is haha
Your slicing means to start from the second element, but what if the list only has one element?
then it shows that role
but if it has no role then it's a empty list
and it doesn't work
And that's when the value is nothing
U should instead do value=[<your list comprehension>] or "No Roles"]
emb.add_field(name = f'roles ({len(roles)})', value= " ".join([role.mention for role in roles]) or "No Roles", inline = False)
if member == None:
member = ctx.author
roles = [role for role in member.roles][1:]
``` these two lines can be done better
member = member or ctx.author like Sniper already mentioned
and just do members.roles[1:]
No need to rebuild the entire list
Yea that too
Hunter I added something cool to my rewrite wrapper!
O, what's that?
collectors?
Imagine using collectors with anti-raid stuff, like if a large amount of members join
that's gonna be amazing
So, in built anti raid system support?
no
It's just a regular listener that waits for the event to be dispatched X amount of times
then it dispatches to the collector with all the data from each event
A collector
Well I never used asyncio as much
!d discord.Member.move_to
await move_to(channel, *, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Moves a member to a new voice channel (they must be connected first).
You must have the [`move_members`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.move_members "discord.Permissions.move_members") permission to use this.
This raises the same exceptions as [`edit()`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member.edit "discord.Member.edit").
Changed in version 1.1: Can now pass `None` to kick a member from voice.
Also since am kinda learning JS (svelte) nowadays, sooo
do you use pyautogui to make discord bots?
No
Btw @pliant gulch take a look at this, was posted in disnake server
Seen it already
He also said something about pycord which made them really made lmao
I don't see how you can say "in the long run we wont be "just a fork" when your project is quite literally a fork
I'd take it seriously if they rewrite the entire code base
Eh, ik... All the forks are just copy pastes, but people use them since no one has any other option cz only a handful of people (excluding me) are willing to change their code to comply with other wrappers
The problem isn't forks, it's the statement they made, as a LITERAL fork
๐my man drank too much, being happy to get to maintain a proper wrapper lib
Most of the pycord commits just contain like 5 or less lines of additions of deletions ๐
At least from the random recent commits lmao
Why do this by yourself
discord already moves people to AFK channels if they go AFK in the guild past the set time
into a set AFK channel you set in settings
Oh I see
But then users would just circumvent this by leaving themselves unmuted
Wait I have something for u
Uhhh nvm, it's not there for members
But that's only for the bot
What timer?
Lemme see...
!d discord.Member.voice
property voice: Optional[discord.member.VoiceState]```
Returns the memberโs current voice state.
Wait @hidden hazel
I am finding that thing
I think u can check if a member is talking
For a ModMail bot, that works on when a user reactions it creates a channel with him and staff and the messages get sent between each the created channel and modmail channel, how exactly should one send the embeds between each channel?
!d discord.VoiceState.self_mute is the max I can find ngl
Indicates if the user is currently muted by their own accord.
Indicates if the user is currently in the AFK channel in the guild.
i also took a look, as ar as im aware, you cannot detect if a user is speaking in discord.py.
Yea that's what we are looking for @patent lark
you can do this with other libraries, but discord.py doesnt have that feature as far as im aware.
negative.
Wait how with disnake?
hmmm
"Do this with other libs"
You might be able to actually lol
how so?
My wrapper can detect people speaking based on websocket messages
Since voice connection requires a websocket connection
i'd assume you could, as i dont find it impossible, but i dont think discord.py actually handles it for you.
So you'd need to do stuff with the internal websocket client of the bot
give me a sec I can prob figure it out
Ah cool
cause my wrapper was implementing voice receive but we only got the packets, haven't decoded them
๐
No ๐
what are you going to do when a user leaves themselves unmuted for points?
No
credit them because you were too lazy to fix a bug within your system?
or you could prevent it all by detecting when they speak?
well there are probably multiple solutions
that being one.
Wait so could you possibly get the audio of the VC?
indeed you can.
Or am I misunderstanding
Hey how do you send a message when the TimeOutError occurs
Hmm. I personally don't like that
Hey how do you send a message when the TimeOutError occurs
I actually really don't like that
well, discord.py doesnt handle that for you.
There has to be a lib in some language which has it implemented
its not a feature that allows you to detect that. we are talking about, changing internals to receive this, or use another lib which may allow it.
there is.
Ah yep found it
can anyone help me please
The gateway sends the voice websocket an Operation code of 5
This is basically dispatched when a User is in a "speaking" state
You'd probably don't want to modify the websocket and listen for the OPCode
I was just curious
Odd discord documentation says it's sent when the client is speaking. But looking at my collaborators voice receive implementation it is dispatched as well for users
I guess this is sort of a grey area
i have a ticket system and whats supposed to happen is i type *createticket <#channel> <message> and that would create an embed with a ticket reaction so people could react to it and talk to staff in the private channel that gets made and whenever i press on the reaction, it makes a new role but it doesnt make a new channel https://mystb.in/RulingMedicaidAccessible.python
Why not modify the ws tho?
because in order to listen for that operation code you'd need to modify the method that listens to the gateway
potentially breaking everything. Overall undefined behaviour
That wrapper hasn't been actively developed in ages, I doubt there is one
๐
what can i do with rb then๐
Oh nevermind I was looking at the old repo
Looks like they moved the repo
oh... its a bit better, but hasn't had a commit since 4 months ago
this one right
wait
theres a channel for it in the discord api server
this one sorry:
https://github.com/shardlab/discordrb
discordrb looks so clean and simple ngl
For a ModMail bot, that works on when a user reactions it creates a channel with him and staff and the messages get sent between each the created channel and modmail channel, how exactly should one send the embeds between each channel?
Hi together!
I am currently splitting my cogs because it starts to get messy. What is the best way to have variables shared within all files?
In the all-in-one cog I just loaded my settings from file into a global variable and wrote it back on changes. Now I can't do that because the settings inside different cogs would drift apart if they all change settings. But I don't really want to load the settings from file every time I need them.
a bot var
Also would it be bad not using a database for this purpose
does the data need to be stored? can it not just be sent straight to a staff channel or whatever?
if it does need to be stored, use a DB for sure
well it's only for one server so i guess i don't need a db
the size doesn't matter
though, how do I send messages between the DM channel and created staff channel, is what I'm confused about
it's not because it's small, that you can use a txt or whatever
Is it possible to make a bot to send message to a channel on terminate
you get the staff channel when you're in a dm, and just send it through
yup, you can overwrite the async close method of the bot
no i mean I don't need to store information like per server configruation
yeah, but you'll probably want the modmail to still be stored when the bot restarts I guess
yeah but how would i tell the bot which channel to send the message to or which member to DM
Is it a good idea to do so? Would I accidentally overwrite something important
by hardcoding that into a variable
STAFF_CHANNEL_ID = ...
just make sure it still has the normal close implementation as last step
but what if for every ticket made it creates a new channel
do you know chambur's modmail?
OK cool. Tq
I'll save you some time
Overwrite Bot.close with what you would like to happen as the bot shuts down to implement "on_close" functionality.
Note: if you are not sub-classing it is recommended that you do so as to avoid over-complications.
class CustomBot(discord.Client): # or inherit commands.Bot
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
...
async def close(self):
# do stuff
await super().close()```
no, idk anything about modmail
Neat, thanks again
well, you can store all the "active ticket channel ID's" as a variable
else print the error
also, ctx comes first, then error
make sure you have the event decorator on top
@bot.listen('on_command_error') recommended
^
well isnt default one just gonna annoy your console ?
why listen? so you can have multiple listeners for the same event?
Why event?
to overwrite default one
since you only need one...
I have listeners in all of my bots it doesn't raise errors
im saying print not raise
ill check when i get on PC
@oblique cobalt I checked it for you (as you can see the console is empty even tho there are no events but only listeners)
async def on_member_join(member):
embed = discord.Embed(description = f"\n\n[#915283231899795526](/guild/267624335836053506/channel/915283231899795526/)\n\n[#917113108420513842](/guild/267624335836053506/channel/917113108420513842/)\n\n[#912080645608587325](/guild/267624335836053506/channel/912080645608587325/)", color=0x36393E)
embed.set_thumbnail(url = member.avatar_url)
await ctx.send(f"welcome {member.mention}")
await client.get_channel(912102049364209684).send(embed=embed)``` help with await ctx.send(f"welcome {member.mention}")
where would i put it
so send a message outside the embed
this is the incorrect listener in a Cog / class
the docs will tell you what is
just look up Cogs and it'll be right ahead
!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.
done
surgeryend = datetime.datetime(2022, 1, 13, tzinfo=ist)
elif localdate > obgend:
def surgery(localdate, surgeryend):
return (localdate - surgeryend)
days = f"{surgery(surgeryend, localdate)}"
medicinestart = surgeryend - localdate
if medicinestart.days <= 1:
await message.reply("Your Next posting `Medicine`, starts tomorrow.")
else:
await message.reply(f"Current Posting: `Surgery`, {':'.join(days.split(':')[0:-1])} hrs to go.")
elif localdate > surgeryend:
def medicine(localdate, medicineend):
return (localdate - medicineend)
days = f"{medicine(medicineend, localdate)}"
cmstart = medicineend - localdate
if cmstart.days <= 1:
await message.reply("Your Next posting `Community Medicine`, starts tomorrow.")
else:
await message.reply(f"Current Posting: `Medicine`, {':'.join(days.split(':')[0:-1])} hrs to go.")```
you don't have to put anything between the (), you can just it like an event, not a listen
in the 1st 1lif
elif*
it worked correctly
now that the date is more than 13/01/2022
it should triger the elif localdate > surgeryend:
but
just print the statement itself, and you'll see if the outcome is as expected
print(localdate > surgeryend)
when i am sending the msg posting it says await message.reply("Your Next posting Medicine, starts tomorrow.")
when it should send await message.reply(f"Current Posting: Medicine, {':'.join(days.split(':')[0:-1])} hrs to go.")
@bot.event outside of a class
is equal to
@commands.Cog.listener()
inside of a Cog
you have to add self as an argument in that method, you're in a class
if that error didn't pop up, you have some messed errorhandlers somewhere
says False
well, then it obviously will never print what you want it to
you can just print every variable and check if it's what you want it to be
that way, you know what's wrong
jsut a sec i messed up while printing xd
print (localdate > surgeryend) is True
since its true it shpuld trigger the
elif localdate > surgeryend:
def medicine(localdate, medicineend):
return (localdate - medicineend)
days = f"{medicine(medicineend, localdate)}"
cmstart = medicineend - localdate
if cmstart.days <= 1:
await message.reply("Your Next posting `Community Medicine`, starts tomorrow.")
else:
await message.reply(f"Current Posting: `Medicine`, {':'.join(days.split(':')[0:-1])} hrs to go.")```
but
How can I make a marry command and it will show whom you married when you type !marrage
its still triggering this only
elif localdate > obgend:
def surgery(localdate, surgeryend):
return (localdate - surgeryend)
days = f"{surgery(surgeryend, localdate)}"
medicinestart = surgeryend - localdate
if medicinestart.days <= 1:
await message.reply("Your Next posting `Medicine`, starts tomorrow.")
else:
await message.reply(f"Current Posting: `Surgery`, {':'.join(days.split(':')[0:-1])} hrs to go.")```
@potent spear
this code is blocking the above code.
just print the medicinestart, you'll see it isn't the value you expect it to be and you can work with that
-4 days, 9:59:55.616750
the value is okay
@client.command()
async def marry(ctx, member: discord.Member):
await ctx.send(f"{ctx.author.name} married {member.name}")```
!marry @copper yarrow
well, -4 is obviously smaller than 1...
so the if statement is true...
well yes but
the point is
it shoul consider the elif localdate > surgeryend: first
But I wanna see who married to whom when I type !marriage
well, that's what'll get sent...
if localdate <= obgend:
elif localdate > obgend:
elif localdate > surgeryend:
i have these 3 statements
it'll never come to the third elif ofc
why not?
becuase if localdate is not <= obgend
it'll obviously be >
you'll need a database for that
Anyone
Wdym?
ah
I need a database for marriage command?
how can i solve this :3
by rethinking your code
not if you don't want this to persist when you restart the bot
if you do, you'll just have to store in a db when you get married and via the "marriage" it'll check who you married to in the db or whatever you like
wait how do i make the bot send a message with all the items in a list without it sending an item each message, like i want all the items to be in 1 message
you can make the list a string via join
google python str.join
i kinda didn't code in python for a while
ok
!join
Joining Iterables
If you want to display a list (or some other iterable), you can write:
colors = ['red', 'green', 'blue', 'yellow']
output = ""
separator = ", "
for color in colors:
output += color + separator
print(output)
# Prints 'red, green, blue, yellow, '
However, the separator is still added to the last element, and it is relatively slow.
A better solution is to use str.join.
colors = ['red', 'green', 'blue', 'yellow']
separator = ", "
print(separator.join(colors))
# Prints 'red, green, blue, yellow'
An important thing to note is that you can only str.join strings. For a list of ints,
you must convert each element to a string before joining.
integers = [1, 3, 6, 10, 15]
print(", ".join(str(e) for e in integers))
# Prints '1, 3, 6, 10, 15'
or that^^
who needs google?
people who need stack overflow
I'm sure 40% of discord.py code on stackoverflow is bad
but i use disnake tho
stackdidnotflow
stackflow
doesn't matter , Disnake is derived from discord
Guys can someone help me?
Sure
its about this
I want to duplicate these to my code
if any(word in message.content for word in["Ghoul", "Town"]):
await message.delete()
sent_message = await message.channel.send('<@&926037413669769228> There is a raid in Ghoul Town starting within 15 minutes.')
hist[message.author.id] = sent_message
if "MASSIVE" in message.content:
if message.author.id in hist:
await message.delete()
await hist[message.author.id].edit(content="**MASSIVE** - <@&926037413669769228> There is a **MASSIVE** raid in Ghoul Town starting within 15 minutes.") ```
but this lines will be changed:
if any(word in message.content for word in["Ghoul", "Town"]):
sent_message = await message.channel.send('<@&926037413669769228> There is a raid in Ghoul Town starting within 15 minutes.')
await hist[message.author.id].edit(content="**MASSIVE** - <@&926037413669769228> There is a **MASSIVE** raid in Ghoul Town starting within 15 minutes.")
Why is it like
in[...]```
There should be a space
space on what?
In this case it will work anyway but it is not following code style conventions I am pretty sure
in [...]```
You want to change the list of available words?
Yeah it's better to write it with a space
in ["Ghoul", "Town"]):```
i want it to detect another specific words instead of
["Ghoul", "Town"])
okay, thanks for the info. i'll change it
Create a list of those words and store it somewhere if you would like to
how can i create a list?
Do you know python well?
Then I don't recommend to start learning it from a discord bot, start with smaller projects
It requires intermediate python knowledge because it is an advanced asynchronous application and just copying code from everywhere won't give you much knowledge
okay
same
without using a database, how would be the best way to have a list of ID's and check/add to that list. Would a json file be okay for this?
isn't json kinda a db?
hmm you can say but not for big projects
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.
@slate swan I won't be helping u in DMs
hwy
ok
async def update_data (users, user):
if not f'{user.id}' in users:
users[f'{user.id)'] = {}
users[f'{user. id}']['experience'] = 0
users[f'{user. id}']['level'] = 1
async def add_experience(users, user, exp):
users[f'{user. id}', ['experience'] +- exp
async def level_up(user, users, message):
with open('levels.json', 'r') as g:
levels = json.load(g)
experience = users[f'{user. id}']['experience']
lvl_start = users[f'{user. id}']['level']
lvlend = int(experience ** (1/4))
if lvl start < lvl_end:
await message.channel.send(f'{user.mention} has leveled up! **TO LEVEL - {lvl_end}')
users [f'{user.1d}']['level'] = lvl_end```
- why is there an event decorator
- the indentation seems inside the
level_upfunc
- a database is better than a json for a levelling system
wt
how did you forgor to say its async def update_data(users, user):
i dont think there is spacing betwee nthe parenthesis and the name
ive fixed that i think but i got a new error and i cant fix it ig
.
ik
U can't find the file?
ye
Weird... what's <fstring>
Sounds like replit is doing good
Facts
My best guess is that it's gonna be in the users.json file
I have not the slightest clue how to help sorry
same
i saw it
what do you recommend I start with when coding a disocrd bot, bcos I wanna make just a simple one for a server for friends
Hi! I get a bearer (or smth like that) from a function.
Looks like this: b'["hello","welcome"]'
How can i count how much words (strings) are in there?
It's speaking for itself
!indents
Indentation
Indentation is leading whitespace (spaces and tabs) at the beginning of a line of code. In the case of Python, they are used to determine the grouping of statements.
Spaces should be preferred over tabs. To be clear, this is in reference to the character itself, not the keys on a keyboard. Your editor/IDE should be configured to insert spaces when the TAB key is pressed. The amount of spaces should be a multiple of 4, except optionally in the case of continuation lines.
Example
def foo():
bar = 'baz' # indented one level
if bar == 'baz':
print('ham') # indented two levels
return bar # indented one level
The first line is not indented. The next two lines are indented to be inside of the function definition. They will only run when the function is called. The fourth line is indented to be inside the if statement, and will only run if the if statement evaluates to True. The fifth and last line is like the 2nd and 3rd and will always run when the function is called. It effectively closes the if statement above as no more lines can be inside the if statement below that line.
Indentation is used after:
1. Compound statements (eg. if, while, for, try, with, def, class, and their counterparts)
2. Continuation lines
More Info
1. Indentation style guide
2. Tabs or Spaces?
3. Official docs on indentation
what did I say? your indents are wrong in the level_up func
?
what part of that sentence do you not understand
Hi! I get a bearer (or smth like that) from a function.
Looks like this: b'["hello","welcome"]'
How can i count how much words (strings) are in there?
can someone help me with this?
await message.delete()
sent_message = await message.channel.send('test')
hist[message.author.id] = sent_message
if "star" in message.content:
if message.author.id in hist:
await message.delete()
await hist[message.author.id].edit(content = "testing")```
if i type "hope", the message gets deleted and the bot sends a message "test". and if i type "star", the message gets deleted and the bot edits the message "test" into "testing".
i have a problem, if i duplicate that code
you are closing the task
if any(word in message.content for word in "hope"):
await message.delete()
sent_message = await message.channel.send('test')
hist[message.author.id] = sent_message
if "star" in message.content and message.author.id in hist:
await message.delete()
await sent_message.edit("testing")
should work with that
no wait, thats not my problem
and change something into this,
await message.delete()
sent_message = await message.channel.send('test')
hist[message.author.id] = sent_message
if "star" in message.content:
if message.author.id in hist:
await message.delete()
await hist[message.author.id].edit(content = "pound")```
@slate swan
this should work
hist = {}
if any(word in message.content.lower() for word in "hope"):
await message.delete()
sent_message = await message.channel.send('test')
hist.append(messager.author.id)
if "star" in message.content and message.author.id in hist:
await message.delete()
await sent_message.edit("testing")
i'll try it
put the hist = {} outside the on_message event
my problem is that when i duplicte that code into my script and change the words inside the "-". it contradicts each other
you don't have to duplicate the code
and you are making a for for one string
should look like this if "hope" in message.content
It's a binary string
Button links in nextcord
!d nextcord.ui.button
nextcord.ui.button(*, label=None, custom_id=None, disabled=False, style=<ButtonStyle.secondary: 2>, emoji=None, row=None)```
A decorator that attaches a button to a component.
The function being decorated should have three parameters, `self` representing the [`nextcord.ui.View`](https://nextcord.readthedocs.io/en/latest/api.html#nextcord.ui.View "nextcord.ui.View"), the [`nextcord.ui.Button`](https://nextcord.readthedocs.io/en/latest/api.html#nextcord.ui.Button "nextcord.ui.Button") being pressed and the [`nextcord.Interaction`](https://nextcord.readthedocs.io/en/latest/api.html#nextcord.Interaction "nextcord.Interaction") you receive.
Note
Buttons with a URL cannot be created with this function. Consider creating a [`Button`](https://nextcord.readthedocs.io/en/latest/api.html#nextcord.ui.Button "nextcord.ui.Button") manually instead. This is because buttons with a URL do not have a callback associated with them since Discord does not do any processing with it.
It's easy
Anyone have any sample coding of reading embed? Any code. Just trying to learn how to. DM me please.
Guys I need help, I would appreciate everyone who could help me.
I got reported on my main for being underage. I appealed it, and it was been a day now. I heard many people never got their accounts back.
So, in case my account gets deleted in 14 days (since I heard when it gets disabled it gets deleted in 14 days) only thing I can do is transfer ownership to other account but it MUST have Moderator/Admin perms.
Well this is a problem, nobody on the Server including bots have those perms (they have mod ones).
Only one that has Admin perms is bot I made, and I have my token. So is there a way I can code a bot to make a role with admin perms and give me it? Thank you.
!d discord.Message.embeds get the discord.Message object, then use this attribute. It returns a list of discord.Embed objects, which have everything you need to read it.
A list of embeds the message has.
Are you in the server?
also if your bot has admin, why cant it just unban you from the guild 
Yes I am.
I'm not banned, my discord is disabled bro- by the discord.
reading embed why?
I sent them proof of me kot being underage.
your bot needs to make a role with admin permissions and then you'd need to give it to yourself
I gave an answer... The initial answer is wrong.
Exactly, so I can transfer ownership on my alt.
Last one is problem for me.
So that's the idea I got
you cant transfer owner if your just an admin though
bruh make a new bot
only the owner of the server can transfer owner
You can send appeal to discord
It owners account gets deleted
make team
oh
Trying to make a BOT. Not rn, tomorrow morning
You can request from discord to transfer
But new accs needs admin perms
So can I make bot to make a role with admin perms and give me that role on alt?
Reading or creating an embed?
That's my question
I already gave them the answer
Reading. So I need it to read an embed sent by another bot, then send output. The output part is easy, I need it to read certain aspects
Brb
yes
Can you help me with code?
anyone know asyncpraw
yes
no
guys can someone help me?
hmm
Can't help if u don't tell the problem
this is my code
await message.delete()
sent_message = await message.channel.send('Ghoultest')
hist[message.author.id] = sent_message
if "MASSIVE" in message.content:
await message.delete()
if message.author.id in hist:
await hist[message.author.id].edit(content = "Massive Ghoultest")
#----------------------------------------------------------------------------
if any(word in message.content for word in ["Slayer", "Army"]):
await message.delete()
sent_message = await message.channel.send('Slayertest')
hist[message.author.id] = sent_message
if "MASSIVE" in message.content:
await message.delete()
if message.author.id in hist:
await hist[message.author.id].edit(content = "Massive Slayertest")```
oh
Ig that's the main issue rest idk
?
what are you using
I'm back. You want to help? Or nah
me need help
When i type Ghoul Town it executes the first if "MASSIVE" in message.content:. and when i type Slayer Army it executes the second if "MASSIVE" in message.content:. But the issue is, when i type Slayer Army again, it executes the first if "MASSIVE" in message.content: not the second if "MASSIVE" in message.content:.
RIP
Hmm, seems like yr bot is lagging and still processing the content of the previous message?
yeah, it seems like it
Also u sure u r writing Slater Army and not Slayer army?
Hello! Anyone who knows how to use buttons, can I talk to them privately?
Sure, ig
nextcord.ui.Button?
Hey guys, I'm trying to work with the discord.py API and learn some fun ways to use it, I'm currently trying to grab all servers and all channels within those servers and write them to folders and files.
I've came across 2 issues, the first is that it seems to be attempting to write all channels for all servers into every server folder (instead of their own independent folders). The second is that the txt files seem to error once they encounter an emoji.
Error:
[ERROR]: Command raised an exception: OSError: [Errno 22] Invalid argument: 'C:\\Users\\me\\Desktop\\main2/logs/HackerOne/๐ธGirls-Only ๐ซ๐ <โ Stinky.txt'
Code:
await ctx.message.delete()
async for guild in client.fetch_guilds():
os.mkdir(f'logs')
os.mkdir(f'{pathlib.Path(__file__).parent.resolve()}/logs/{guild}')
for channels in client.get_all_channels():
ff = open(f'{pathlib.Path(__file__).parent.resolve()}/logs/{guild}/{channels}.txt', 'w', encoding='utf-8')
ff.write(f'test')
await asyncio.sleep(25)
print(f'{Fore.GREEN}Success!')
(yes I know this is awful but I'll clean it up with error handling when it's behaving as it should)
I should add that without writing the text files, this will create a folder for every server. It's just struggling to handle emojis it seems and adding all servers channels into each folder
thats a weird path
property guilds: List[discord.guild.Guild]```
The guilds that the connected client is a member of.
It just grabs the present working directory with pathlib
Hello! Can I talk to someone who used discord components?
I've tried literally everything I can think of by this point and now I'm just stuck
Ran out of ideas
It's not recommended to use a third party library. Use the master branch , or some fork
a person who violates TOS
How is it against TOS?
can I put a var in a decorator inside a class?
@nextcord.ui.Button(label="Reddit",style = nextcord.ButtonStyle.green,url = total_link) #total_link
async def memedata(self,button:nextcord.ui.Button,interaction:nextcord.Interaction):```
i tried to execute the code with an interval of 10 min but it still executes the 1st if "MASSIVE" in message.content: i think the bot doesnt recognize the 2nd if "MASSIVE" in message.content: and only executes the 1st if "MASSIVE" in message.content: since it's placed higher than the second one.
it doesent find the var in the init
CODE:
await message.delete()
sent_message = await message.channel.send('Ghoultest')
hist[message.author.id] = sent_message
if "MASSIVE" in message.content:
await message.delete()
if message.author.id in hist:
await hist[message.author.id].edit(content = "Massive Ghoultest")
#----------------------------------------------------------------------------
if any(word in message.content for word in ["Slayer", "Army"]):
await message.delete()
sent_message = await message.channel.send('Slayertest')
hist[message.author.id] = sent_message
if "MASSIVE" in message.content:
await message.delete()
if message.author.id in hist:
await hist[message.author.id].edit(content = "Massive Slayertest")
ISSUE:
When i type Ghoul Town it executes the first
if "MASSIVE" in message.content:
and when i type Slayer Army it executes the second
if "MASSIVE" in message.content:
. But the issue is, when i type Slayer Army again, it executes the first
if "MASSIVE" in message.content:
not the second
if "MASSIVE" in message.content:
My opinion
i think the bot doesnt recognize the 2nd
if "MASSIVE" in message.content:
and only executes the 1st
if "MASSIVE" in message.content:
since it's placed higher than the second one.
How can i fix it guys? thanks for helping!
Bro how can I remove add to server feature from my bot
Discord Dev Website > OAuth2 > General
What about in bot section?
Ah wait I just saw, why do u have two if statements with the same thing?
?
if any(word in message.content for word in ["Ghoul", "Town"]):
or
if "MASSIVE" in message.content:
?
Hiw
about that
Help me
Only one of them will execute, the first one, since that's first in order
Should I enable public bots in bots section
Yea
Why?
U need to make it a public bot
I don't want anyone to add it
Then forget about the Add to Server button
K. Then how to remove add to server option
Yes I don't want that
Set it to None in the OAuth2 Tab
How to remove
And this?
No
they are two since the first one is:
await hist[message.author.id].edit(content = "Massive Ghoultest")```
while the second one is:
```if message.author.id in hist:
await hist[message.author.id].edit(content = "Massive Slayertest")```
# I imported the other modules
async def mute(self, ctx: commands.Context, member: Member, timer="15m", *, reason):
long = humanfriendly.parse_timespan(timer)
await member.edit(
timeout=utils.utcnow() + datetime.timedelta(seconds=long)
)
I am getting this error (I never got it before)```
File "/home/runner/Efendo-Bot-Source-Code/modules/mod/cog.py", line 130, in mute
await member.edit(
TypeError: edit() got an unexpected keyword argument 'timeout'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/nextcord/ext/commands/bot.py", line 995, in invoke
await ctx.command.invoke(ctx)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/nextcord/ext/commands/core.py", line 895, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/nextcord/ext/commands/core.py", line 177, in wrapped
raise CommandInvokeError(exc) from exc
nextcord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: edit() got an unexpected keyword argument 'timeout'```
This command used to work before but it dosn't work anymore.
Any idea what is wrong with it?
But the bot won't know when to go to the second statement, soooo
how can i make it so the 2nd one will be executed with a specific action?
Wrong version
Idk what u tryna do, sooo
wdym?
ok... lemme reinstall
@maiden fable what is the correct nextcord version?
so basically, if i type Slayer Army, it will execute the second
if "MASSIVE" in message.content:
since it's under the if-statement of
if any(word in message.content for word in ["Slayer", "Army"]):
and when i type Ghoul Town, it will execute the first
if "MASSIVE" in message.content:
since it's under the if-statement of
if any(word in message.content for word in ["Ghoul", "Town"]):
Here's how to format Python code on Discord:
```py
print('Hello world!')
```
These are backticks, not quotes. Check this out if you can't find the backtick key.
The indentation is all messed up
This is how it's shown in my mobile
So format your code with codeblocks plz
use three backticks
Yea
i ask again lol
if any(word in message.content for word in ["Ghoul", "Town"]):
await message.delete()
sent_message = await message.channel.send('Ghoultest')
hist[message.author.id] = sent_message
if "MASSIVE" in message.content:
await message.delete()
if message.author.id in hist:
await hist[message.author.id].edit(content = "Massive Ghoultest")
#----------------------------------------------------------------------------
if any(word in message.content for word in ["Slayer", "Army"]):
await message.delete()
sent_message = await message.channel.send('Slayertest')
hist[message.author.id] = sent_message
if "MASSIVE" in message.content:
await message.delete()
if message.author.id in hist:
await hist[message.author.id].edit(content = "Massive Slayertest")
Did it for u
See yr indent
Where is my intend wrong?
is there anyway i can put this code
if "MASSIVE" in message.content:
await message.delete()
if message.author.id in hist:
await hist[message.author.id].edit(content = "**MASSIVE** - <@&926037277833048115> There is a **MASSIVE** raid in Slayer Army starting within 15 minutes.")
under this one?
if any(word in message.content for word in ["Slayer", "Army"]):
await message.delete()
sent_message = await message.channel.send('<@&926037277833048115> There is a raid in Slayer Army starting within 15 minutes.')
hist[message.author.id] = sent_message
so when this
if any(word in message.content for word in ["Slayer", "Army"]):
await message.delete()
sent_message = await message.channel.send('<@&926037277833048115> There is a raid in Slayer Army starting within 15 minutes.')
hist[message.author.id] = sent_message
is executed
this
if "MASSIVE" in message.content:
await message.delete()
if message.author.id in hist:
await hist[message.author.id].edit(content = "**MASSIVE** - <@&926037277833048115> There is a **MASSIVE** raid in Slayer Army starting within 15 minutes.")
will also execute
seriously? json?
It's Sang Eun Ha's code
see the number of spaces
Just to confirm, one can have two @bot.listen() functions in the same main file right? I seem to have forgotten
oh lol
yes
you can
Where? It seems good to me. I must be blind
tab them again
two @bot.listen for on_messages won't be any different right?
they'll be the same, you can name the functions differently
keep the events same
help pls
what you can't do is use two on_message events for @bot.event then, correct?
yep
okay thanks
@bot.listen("on_message")
async def first_on_message: pass
@bot.listen("on_message")
async def second_on_message: pass
welcome
@slate swan his/her code and problem is above
^^^
if any(word in message.content for word in ["Slayer", "Army"]):
``` you know this returns a list of Booleans right?
Uh
word in message.content are the values it will return , which would be a bool
!e
if any(word in "slayer" for word in ["Slayer", "Army"]):
print(1)
It still works (:
@maiden fable :warning: Your eval job has completed with return code 0.
[No output]
See
so what problem happens with the 2nd statement>
@slate swan
So I have this command (going to be a task event which runs every 6 - 24 hours, eventually) which searches through a channels history to find msgs that have embeds which match a list of keywords. I
- want my bot to look through the fetched msgs chronologically (oldest to newest)
- then for every message in that list I want to check if the message ID is not in my list of checked messages
- then I want it to check if the author of the msg is the same as the provided ID
- then I want it to check if the message contains a embed (It should do every time but doing this to be on the safe side)
- then I want it to check if any of the words in my
key_wordslist appear in the embeds title- if the
key_wordsdo appear then I want it to construct a new embed from the field values of the original embed- then I want it to add the ID of the message it just checked to my list of checked msgs so that it won't check it again in future
I think I have all of that logic correct but does someone mind checking over my code to double check this for me?
I also have some additional stages that I'm not too sure how to implement so some idea's on how I could do them would be appreciated.- I would like to be able to know which of my
key_wordsit triggers on so that I can add that to my new embed inside of the{action}variable- I would like to write the datetime timestamp of the last checked message to my
last_chackedvariable so that it won't check msgs before that again (jut saving on having duplicate new embeds)
Below is my code, thank for you reading```py
@commands.command()
@commands.has_permissions(administrator = True)
async def moderation_logs(self, ctx):
key_words = ["WARN", "MUTE", "UNMUTE", "KICK", "BAN", "UNBAN"] # Add in Captilised versions of each word to account for the Dyno logs
checked_logs = []
case_count = 0
last_checked = 0
#dict = {}
moderation = self.bot.get_channel(id = 885569667861717042)
clifford_log = self.bot.get_channel(id = 500768218257031168)
with moderation.channel.typing():
messages = await clifford_log.channel.history(oldest_first = True, limit = None, after = last_checked).flatten() # 10000
for message in messages[0:]: # Making bot search history chronologically
if message.id not in checked_logs:
if message.author.id == 776782769312628746:
if len(message.embeds) > 0:
if key_words in message.embeds[0].title:
embed = discord.Embed(title = f"Case {case_count} | {action}", colour = self.bot.config.error_colour, timestamp = message.timestamp)
embed.set_author(name = f"{message.embeds[0].fields[0].value} | {message.embeds[0].fields[0].value.id}", icon_url = message.embeds[0].fields[0].value.avatar_url)
embed.set_footer(text = f"{message.embeds[0].fields[1].value} | {message.embeds[0].fields[1].value.id}", icon_url = {message.embeds[0].fields[1].value.avatar_url})
embed.add_field(name = "Offender", value = message.embeds[0].fields[0].value, inline = True)
embed.add_field(name = "Moderator", value = message.embeds[0].fields[1].value, inline = True)
if message.embeds[0].fields[3]:
embed.add_field(name = "Duration", value = message.embeds[0].fields[3].value)
if message.embeds[0].fields[2]:
embed.add_field(name = "Reason", value = message.embeds[0].fields[2].value)
checked_logs.append(message.id)
await moderation.send(embed = embed)```
hi, i have a server with 1700 bans and i need help with an unban all command,
@bot.command(pass_context=True)
@commands.has_permissions(administrator=True)
async def unban(ctx):
server=ctx.guild
ban_list=await bot.get_bans(server)
await ctx.send('Desbaneando a todos los miembros.')
for member in ban_list:
await bot.unban(server,member)```
The bot doesn't unban anyone
And it doesn't print any traceback
Itโs guild.bans() not get_bans()
class RedditLink(nextcord.ui.View):
def __init__(self,link,permalink):
self.reddit_link = link
self.permalink = permalink
self.total_link = self.link + self.permalink
@nextcord.ui.Button(label="Reddit",style = nextcord.ButtonStyle.green,url = self.total_link)
async def link(self,button:nextcord.ui.Button,interaction:nextcord.Interaction):
pass```
it doesent find self.total_link
ban_list=await bot.guild.bans(server) like this?
Just bans(). No parameters
okay
Make sure the tutorial u looked at is up to date
so the server=ctx.guild is innecesary?
Technically yes, but the way u have it is fine
what why bot
That way is wrong btw
Doesnโt it have bot.guilds?
Which is a list
.bans() is for a single server
await ctx.guild.unban(member) can i do it like this?
@bot.command(pass_context=True)
async def unban(ctx):
if ctx.author.id == 626127081419571206 or 931999712012275732:
ban_list=await bot.guild.bans()
await ctx.send('Desbaneando a todos los miembros.')
for member in ban_list:
await ctx.guild.unban(member)
else:
await ctx.send('ยกNo tienes permisos para ejecutar ese comando!')```
it looks like this
!tag or-gotcha
When checking if something is equal to one thing or another, you might think that this is possible:
if favorite_fruit == 'grapefruit' or 'lemon':
print("That's a weird favorite fruit to have.")
While this makes sense in English, it may not behave the way you would expect. In Python, you should have complete instructions on both sides of the logical operator.
So, if you want to check if something is equal to one thing or another, there are two common ways:
# Like this...
if favorite_fruit == 'grapefruit' or favorite_fruit == 'lemon':
print("That's a weird favorite fruit to have.")
# ...or like this.
if favorite_fruit in ('grapefruit', 'lemon'):
print("That's a weird favorite fruit to have.")
ANY HELP?
ban_list = await ctx.guild.bans()
hey guys how can i make my slash commands say something to the user and only they can see it
ephemeral = True
where would i add that, in the @slash part?
what are you using for module
discord_slash
because its BAD
use nextcord
is it just a fork or is it completely different
hmm
a fork and better
instead of discord
nextcord
will all my code break when i do upgrade
discord.Embed -> nextcord.Embed
depends
or just import nextcord as discord
deinstall discord
So I have this command (going to be a task event which runs every 6 - 24 hours, eventually) which searches through a channels history to find msgs that have embeds which match a list of keywords. I
- want my bot to look through the fetched msgs chronologically (oldest to newest)
- then for every message in that list I want to check if the message ID is not in my list of checked messages
- then I want it to check if the author of the msg is the same as the provided ID
- then I want it to check if the message contains a embed (It should do every time but doing this to be on the safe side)
- then I want it to check if any of the words in my
key_wordslist appear in the embeds title- if the
key_wordsdo appear then I want it to construct a new embed from the field values of the original embed- then I want it to add the ID of the message it just checked to my list of checked msgs so that it won't check it again in future
I think I have all of that logic correct but does someone mind checking over my code to double check this for me?
I also have some additional stages that I'm not too sure how to implement so some idea's on how I could do them would be appreciated.- I would like to be able to know which of my
key_wordsit triggers on so that I can add that to my new embed inside of the{action}variable- I would like to write the datetime timestamp of the last checked message to my
last_chackedvariable so that it won't check msgs before that again (jut saving on having duplicate new embeds)
Below is my code, thank for you reading```py
@commands.command()
@commands.has_permissions(administrator = True)
async def moderation_logs(self, ctx):
key_words = ["WARN", "MUTE", "UNMUTE", "KICK", "BAN", "UNBAN"] # Add in Captilised versions of each word to account for the Dyno logs
checked_logs = []
case_count = 0
last_checked = 0
#dict = {}
moderation = self.bot.get_channel(id = 885569667861717042)
clifford_log = self.bot.get_channel(id = 500768218257031168)
with moderation.channel.typing():
messages = await clifford_log.channel.history(oldest_first = True, limit = None, after = last_checked).flatten() # 10000
for message in messages[0:]: # Making bot search history chronologically
if message.id not in checked_logs:
if message.author.id == 776782769312628746:
if len(message.embeds) > 0:
if key_words in message.embeds[0].title:
embed = discord.Embed(title = f"Case {case_count} | {action}", colour = self.bot.config.error_colour, timestamp = message.timestamp)
embed.set_author(name = f"{message.embeds[0].fields[0].value} | {message.embeds[0].fields[0].value.id}", icon_url = message.embeds[0].fields[0].value.avatar_url)
embed.set_footer(text = f"{message.embeds[0].fields[1].value} | {message.embeds[0].fields[1].value.id}", icon_url = {message.embeds[0].fields[1].value.avatar_url})
embed.add_field(name = "Offender", value = message.embeds[0].fields[0].value, inline = True)
embed.add_field(name = "Moderator", value = message.embeds[0].fields[1].value, inline = True)
if message.embeds[0].fields[3]:
embed.add_field(name = "Duration", value = message.embeds[0].fields[3].value)
if message.embeds[0].fields[2]:
embed.add_field(name = "Reason", value = message.embeds[0].fields[2].value)
checked_logs.append(message.id)
await moderation.send(embed = embed)```
if I have my code shared up in different files and one file is for all events. how do I load the events in the main file so it all works? do I have to use cogs, in that case how would it work? or is there an another way to do it?
discord.py isnt working it says syntax error
It seems like you want to import the whole file to your main file. If so you can say from folder.folder import file
replace folder.folder with the path to the file
still need help with the unban all command, i have this
@bot.command()
@commands.has_permissions(administrator=True)
async def unban(ctx):
ban_list = ctx.guild.bans()
await ctx.send('Desbaneando a todos los miembros.')
for member in ban_list:
await ctx.guild.unban(member)```
someone?
What is the error/issue
yea I was thinking about that at first, but if I just import it like that it wont actually start the events when I run the bot
it says that for every command i try to use
no traceback and the bot does nothing
Do it on cmd @misty vault
You could put all the events in a class, and import the class, then call the class so it runs everything
Since this is an async function, I would await the context.guild.bans()
okay, I havent used classes a lot but I will look into that. thanks!
how long does discord take to pop up slash commands on all my servers
all servers the bots in
around 1 hour iirc
ban_list = await ctx.guild.bans() this?
does the script need to be running
You have to specify guild ids in the decorator, for testing purposes. There is probably another way to do it if you want it in all guilds
and once i update the slash commands, it also takes 1 hour?
i dont think so
Yes
@commands.has_any_role(*_CONFIG["bot_manager"])
How do I update that variable? I manage to update it using a command but it doesnt respond to the new role I assign. I am typing the role correctly.
i will try and i tell u
There is probably an issue with the event loop
i just have a funtion that gets all guilds when the bot starts and when bot leaves/joins a server
with a list it just appends
same thing @slim ibex
with the bot code? or just the cmd code
@bot.command()
@commands.has_permissions(administrator=True)
async def unban(ctx):
ban_list = await ctx.guild.bans()
await ctx.send('Desbaneando a todos los miembros.')
for member in ban_list:
await ctx.guild.unban(member)```
I would probably pass in member as a nob-keyword arg and make sure to use the member name and discriminator because that is how you will unban the user
binds
I think that is not the issue, i did a simple command and it doesnt work, and i dont know why
@bot.command()
async def test(ctx):
await ctx.send('adsa')```this doesnt work XD
where is cmd
Command prompt
nop
no bc the logs work
Ye I was gonna get to that
is it this
Windows+R and type CMD
so how can i make it return the list of members
You donโt want a list of members if you only want to unban one at a time
Thatโs why I said you have to access the ban list like you already are and use the member name and discriminator
how i can do that? i dont understand xd
it says pip is not recognized as a intern or extern command
@misty vault you prolly donโt have python installed properly
Make a variable for member name and discriminator, and make sure to split it with #
and you also will need member as a non keyword arg in the function parameter
for member in ban_list:
member= f"{member.name}#{member.discriminator}"
await ctx.guild.unban(member)``` like this?
Or just some sort of arg
I mean you COULD do it that way
Itโs just you need the member argument if you want to specify the user to unban while typing the command
I believe so
@bot.command()
@commands.has_permissions(administrator=True)
async def unban(ctx):
ban_list = await ctx.guild.bans()
await ctx.send('Desbaneando a todos los miembros.')
for member in ban_list:
member= f"{member.name}#{member.discriminator}"
await ctx.guild.unban(member)```so this should work?
i will host it in another bot bc it dont works and idk why (i did something wrong with the logs)
its IDLE Shell 3.10.1
this is giving me a KeyError for 'formats'? how do i go about fixing that?
yes like in the async(ctx) i can do another
async def a(ctx,a:str=None)
but i only want to unban everyone
OH
can i invite u to replit and u help me? bc i thing its cause of the logs
and i dont know why
First you want to reference the server, and next reference the ban list for said server
then you want to loop over every member in the ban list and unban them
Is there any way for me to auto-reload a cog without needing to run a command?
server=ctx.guild
ye prettt much
ban_list = await server.guild.bans() ?
no
how it would be?
bot.get_bans(server)
anybody?
restart your bot
@bot.command()
@commands.has_permissions(administrator=True)
async def unban(ctx):
server=ctx.guild
ban_list = await bot.get_bans(server)
await ctx.send('Desbaneando a todos los miembros.')
for member in ban_list:
member= f"{member.name}#{member.discriminator}"
await ctx.guild.unban(member)```
it doesn't
I dont particularly want to restart my bot XD
@slim ibex can i invite u to the replt?
not home Iโm on my phone rn
bot = commands.Bot(command_prefix=".", intents=intents, owner_id=725708506556268605,help_command=None)
anybody help me pls?

so nobody, noproblem
where? 
a fact thus uses the interaction of the dadjoke so that it is not the same time
Which line raises the error
None of them, they just run. However, when the fact is above the nanny, fact uses nannyjos, vice versa when it writes an error code under the button.
google translate
it has to do something with the instance (self)
so i invite u maybe to 1 random test server and i show u
Im trying to load my commands from a different file to the main file with classes. its not working, Im guessing I did something wrong but Im not sure what I did wrong. I got it like this
class vc_c(commands.Cog):
def __init__(self, bot: commands.Bot):
self.bot = bot
# Joins VC
@commands.command()
async def join(ctx):
if ctx.author.voice is None:
await ctx.send(f"Please, may {username} join a voice channel for me to direct to!")
voice_channel = ctx.author.voice.channel
if ctx.voice_commands is None:
await voice_channel.connect()
else:
await ctx.voice_commands.move_to(voice_channel)
def setup(bot: commands.Bot):
bot.add_cog(vc_c(bot))
Main file here (I didnt show the whole main file bcz its just so many imports and other shit):
bot.load_extension("vc_c")
print("Online")
bot.run('TOKEN')
I canโt at the moment
ok
btw ty, i try remove from cogs and import for the main
Are the cogs in a seperate folder
well yes, the first code I showed is in my vc_commands.py file and the last part is main.py
ah, yea all of them is in same folder
here u see
I mean it wouldnt make any different?
ehh just more organized
oh okay
I guess thatโs just me
but this is what I mean
for filename in os.listdir("./src/cogs"):
if filename.endswith(".py"):
self.load_extension(f"src.cogs.{filename[:-3]}")
ah, okay. then I would have to create a new folder and have all the cogs there, I will try with that thanks
but it would work with doing it in this way, right? with the separated folder
how do I get every string from this binary?
'b["hello","world"]'
help plz^
!ytdl
Per Python Discord's Rule 5, we are unable to assist with questions related to youtube-dl, pytube, or other YouTube video downloaders, as their usage violates YouTube's Terms of Service.
For reference, this usage is covered by the following clauses in YouTube's TOS, as of 2021-03-17:
The following restrictions apply to your use of the Service. You are not allowed to:
1. access, reproduce, download, distribute, transmit, broadcast, display, sell, license, alter, modify or otherwise use any part of the Service or any Content except: (a) as specifically permitted by the Service; (b) with prior written permission from YouTube and, if applicable, the respective rights holders; or (c) as permitted by applicable law;
3. access the Service using any automated means (such as robots, botnets or scrapers) except: (a) in the case of public search engines, in accordance with YouTubeโs robots.txt file; (b) with YouTubeโs prior written permission; or (c) as permitted by applicable law;
9. use the Service to view or listen to Content other than for personal, non-commercial use (for example, you may not publicly screen videos or stream music from the Service)
noted
File "C:\Users\zined\AppData\Local\Programs\Python\Python310\lib\site-packages\sdl2\dll.py", line 328, in <module>
dll = DLL("SDL2", ["SDL2", "SDL2-2.0", "SDL2-2.0.0"], os.getenv("PYSDL2_DLL_PATH"))
File "C:\Users\zined\AppData\Local\Programs\Python\Python310\lib\site-packages\sdl2\dll.py", line 200, in __init__
raise RuntimeError("could not find any library for %s (%s)" %
RuntimeError: could not find any library for SDL2 (PYSDL2_DLL_PATH: unset)
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\zined\Downloads\Pokemon - Blue Version (UE)[!]\Sblerboy-Open-Source-main\sblerboy.py", line 3, in <module>
from pyboy import PyBoy
File "pyboy\__init__.py", line 14, in init pyboy.__init__
File "pyboy\pyboy.py", line 1, in init pyboy.pyboy
File "pyboy\core\__init__.py", line 6, in init pyboy.core.__init__
File "pyboy\core\mb.py", line 1, in init pyboy.core.mb
File "pyboy\core\sound.py", line 13, in init pyboy.core.sound
File "C:\Users\zined\AppData\Local\Programs\Python\Python310\lib\site-packages\sdl2\__init__.py", line 3, in <module>
from .dll import get_dll_file, _bind
File "C:\Users\zined\AppData\Local\Programs\Python\Python310\lib\site-packages\sdl2\dll.py", line 330, in <module>
raise ImportError(exc)
ImportError: could not find any library for SDL2 (PYSDL2_DLL_PATH: unset)```
its giving me 765763574256475756 errirs right as i thought it worked
This isn't an issue related to discord bots
^
Go to #python-discussion or #โ๏ฝhow-to-get-help
Read the channel description
Does your error have anything to do with any relevant discord bot development libraries?
not work i delet the vsc and i broke my pc. I've been messing with this shit for 4 days, but no one could help me and I couldn't find anything useful anywhere.

Use pathlib 
is there a way so i dont have to specify each server id for the bots slash commands?
which lib
discord
dpy doesn't have slash commands
well discord_slash
Still looking for a little help with this if possible
import discord
from discord.ext import commands
client = commands.Bot(command_prefix='p!')
@client.event
async def on_ready():
print("Bot is on")
client.run = ('TOKEN')
``` I got a new pc and i tried running a basic bot but all im getting is exit code 0 and im not sure why
try
client.run('token', bot=False)
How would I make it so that after I execute a command, the bot still answers me even though I don't have to do the command again?
Example:
Me: !start
Bot: How are you, p4nic?
Me: Fine/Bad
Bot: keep answering...
If I said "fine" it would do something. If I said "bad" it would do something else.
exit code 0 means that the program completed successfully, with no errors. Like said above, you need to call client.run, not reassign it.
With discord.py, you can use wait_for
!d discord.Client.wait_for
wait_for(event, *, check=None, timeout=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Waits for a WebSocket event to be dispatched.
This could be used to wait for a user to reply to a message, or to react to a message, or to edit a message in a self-contained way.
The `timeout` parameter is passed onto [`asyncio.wait_for()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.wait_for "(in Python v3.9)"). By default, it does not timeout. Note that this does propagate the [`asyncio.TimeoutError`](https://docs.python.org/3/library/asyncio-exceptions.html#asyncio.TimeoutError "(in Python v3.9)") for you in case of timeout and is provided for ease of use.
In case the event returns multiple arguments, a [`tuple`](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.9)") containing those arguments is returned instead. Please check the [documentation](https://discordpy.readthedocs.io/en/master/api.html#discord-api-events) for a list of events and their parameters.
This function returns the **first event that meets the requirements**...
anyone know how to make an shop/inventory system with sqlite3?
ty
oh ok thx
Why are you setting the bot kwarg to false
hmmmmmmmm
selfbot lol
Not that I would do that of course
With it being against ToS and all
Mhm
pretty sure they removed that kwarg too
works fine for me
Anyone here well versed with python who thinks they could lend me a quick hand?
just ask, this is the python server so there probably are people that can help :)
I have several times haha no reply
only on master branch
@novel apex
hm sorry bud, not too sure tbh
It's cool I'm sure someone would be able to help eventually ๐
in 1.5/1.7 iirc
Yeah but how would I filter it out? re.sub only accepts a string not an array
tried so many different things to filter out bad chars lol
The funny thing if I copy that filename and create it manually it works
just python can't handle it
how can i count the amount of roles on a server
@Bot.command()
async def serverstats(ctx):
embed=discord.Embed(title=f"Server stats {ctx.guild.name}")
embed.add_field(name="Users:", value=ctx.guild.member_count, inline=False)
embed.add_field(name="Roles:", value=ctx.guild.role_count, inline=False)
#embed.add_field(name="Channels:", value=len(ctx.guild.channels), inline=False)
await ctx.send(embed=embed)```
len(guild.roles)
ii tried this but ya lol
^
because its ctx.guild.roles in your case
what he gave was not so that u can just copy and paste
why people don't use f strings
Lol
hi, anyone knows why I get this problem?
this is the code
class main(commands.Cog):
def init(self, Bot):
self.bot = Bot
def init(self, Bot):
pass
# Joins VC
@commands.command()
async def join(self, ctx):
if ctx.author.voice is None:
await ctx.send(f"Please, may {ctx.author} join a voice channel for me to direct to!")
voice_channel = ctx.author.voice.channel
if ctx.voice_bot is None:
await voice_channel.connect()
else:
await ctx.voice_bot.move_to(voice_channel)
def setup(bot):
bot.add_cog(main(bot))
i did that right after i sent that pic but it didnt work lol
bot=False???
ctx.bot.voice
this uh
oh, jeez I keep doing these dumb mistakes
what was the error?
that didnt fix it, still getting errors
Show
i think i can fix myself
thats not even where the error is lmao
okay cool
oh shoot!
@surreal sierra u wanna check if the bot is there in a voice channel?
yea, if the bot is not already in the voice channel it will join it
!d discord.Guild.voice_client
property voice_client: Optional[VoiceProtocol]```
Returns the [`VoiceProtocol`](https://discordpy.readthedocs.io/en/master/api.html#discord.VoiceProtocol "discord.VoiceProtocol") associated with this guild, if any.
๐
thnx for the help guys
@slate swan what was that attr, something like bot.voice.channel no? I forgot the attr
it works now, thanks!
Guild.me.voice would not be NOne if the bot is in an vc
Oh, hmmm
Guild.voice_client and Context.voice_client works too
probably not
Yea that's sad
re.sub("[\\\/:*<>|]", "", filename)
i never imagined using decorators for command arguments but now im doing it
Wym
hikari things , they implemented prefix and slash commands together , and the arguments are accessed with Context.options.<argname>
for hikari-lb
@info_plugin.command
@add_cooldown(10, 2, bucket=UserBucket)
@option(
name="emoji",
description="Emojo to get information about",
type=Emoji,
required=True,
)
@command(name="emoji", description="Infor about an Custom Emoji", aliases=["emojiinfo"])
@implements(PrefixCommand, SlashCommand)
async def emoji_info_cmd(ctx: Context):```

but it kinda makes life easier by allowing prefix and slash command implements in the same function
Wait whaaa
But good implementation tho
BTW why can't u add args by adding them in function?? It's just sooo easier and readable
also , the plugins ( yes , the cogs in hikari-lightbulb ) are too easy
can I say that hikari is sexy
fails for slash commands
Why
Ass
slash commands have optional args , so it would have been hard to add it along with prefix ones
If the bot is only on two guilds, would there be cache issues on bot.get_guild andguild.get_member?
No?
Meaning will they ever return None
Ah yess... Understandable
this will work one hundred percent of the time right?
๐ณ without any doubts
@spring flax cache never depends on the number of guilds, be it 2 or 200. It will be cached the same way always
so are you saying get_member will always return a discord.Member object in my case?
if you have member intents , yes
Well I don't really know about "always", but in most of the cases, provide the time and circumstances are normal, it should not return None
and the ID Needs to be correct
And by normal, I mean stuff like correct ID (yes Sarthak), not having a connection issue and providing the bot with enough resources to run on
it's for a modmail bot, so it's an on_message in DM's.
guild = bot.get_guild(ID)
guild.get_member(message.author.id)
But I prefer it working hundred percent of the time
BTW why u making your own modmail? Just saying, that it's already on GitHub, the original bot
Yea...
Both
The original one, made for entire discord, and this server's
Wait I ain't sure about @novel apex
Idk, I'm also confused now
There are soo many imposters
This is the original bot, according to me
i thought I read somewhere that it can't be hosted on windows
is that true?
Idk, I never hosted it
But I don't think there should be any issue
Since u r a Python Intermediate-Professional, and not a beginner or smth
wait were you telling to use them or to fork and make my own version
The modmail bot made by kyb3r is the original one
You can tell by the dates the licenses were commit as well
Kyb3r first started the project in 2017 and chamburr started in 2019
nope, complete beginner
honestly I find those bots too complicated
I mean I just need it for one server
And there are so many lines of code and files in Kyb3r's
This is probably for of a python question rather than a discordpy one, but here it is.
I am sending an embed like this. EmCons.py is the name of the file where I'm storing embed constants. Talker is the function I've made to return the embed.
await channel.send(embed=EmCons.Talker(ctx.author.id ,message)) #How I'm calling it
def Talker(intman:int , message):
return Embed(title=f"Message from {hex(intman)[2:]}: ", description=f"{message}", color=0xff69b4)
This is the function in the EmCons file. This gives me the error
Command raised an exception: TypeError: Talker() takes 1 positional argument but 2 were given
The same code worked fine when I only had message as an argument. Not sure where I'm going wrong.
Same, but no complaining if u r learning new things
is there an event for error handling in the on_message event?
im tryna run my bot but this keeps coming up, any ideas on what the problem is?
like on_message_error or smth?
uh
you spelt client wrong
oh
@nextcord.ui.button(label="Comments",style=nextcord.ButtonStyle.green)
async def comments(self,button:nextcord.ui.Button,interaction:nextcord.Interaction):
submission = await reddit.submission(id = self.post.id)
nl = "\n"
comments = f"**[{submission.title}]({reddit.config.reddit_url + submission.permalink})**{nl}{nl}"
for comment in submission.comments:
if len(comments) < 4096:
comments += f"[{comment.author}]({reddit.config.reddit_url + comment.permalink}): {comment.body}{nl}{nl}"
embed = nextcord.Embed(title="",description = comments,colour = interaction.user.colour)
await interaction.response.send_message(embed = embed,view = Delete_View())```In data.embeds.0.description: Must be 4096 or fewer in length.
client = discord.Client()
it's fine
although it's better to use discord.ext.command.Bot instead of client
but it's your choice
yes
any help?
commands.Cog?
are you using freecodecamp
ye
then
class cmd(commands.Cog):```
https://vcokltfre.dev/
try this
A tutorial on how to use discord.py to create your own Discord bot in Python, written to fix the flaws of many other popular tutorials.
thx
it will make sure you use cogs and make better habits yknow
ok
You miss spelled client you put cleint
i saw
Kk
So I changed my system to always have my database open
Now what?
Do I need to change anything else?
nice
Would I just remove the parts where I open and close the database?
Also, do I need to like refresh it or smth
As long as u r commiting everytime, no
Oh hi there link
Yay
HI! I wanted to tell you that i figured out what was wrong LOL
But then, it's just one single line of code
Mind enlightening me?
so one of the solutions you gave me did end up working but I had typed it in wrong initially. turns out that doing pip3 install โDiscordUtils[voice]โ worked but it needed to be exactly like that since I was on a mac so it was using a zch shell
I think I had dropped the single quotes and did pip instead of pip3
but seriously man I have to thank you for working so hard to try and solve my problem. Genuinely appreciate it very much
Weird... Nothing like that on Windows
It's fine, @slate swan actually helped u more than i did haha
yeah this chat and all itโs help is amazing
Agreed
what font is that?
deadass looks like OpenDyslexic
@nextcord.ui.button(label="Comments",style=nextcord.ButtonStyle.green)
async def comments(self,button:nextcord.ui.Button,interaction:nextcord.Interaction):
submission = await reddit.submission(id = self.post.id)
nl = "\n"
comments = f"**[{submission.title}]({reddit.config.reddit_url + submission.permalink})**{nl}{nl}"
for comment in submission.comments:
if len(comments + f"[{comment.author}]({reddit.config.reddit_url + comment.permalink}): {comment.body}{nl}{nl}") >= 4093:
comments += "..."
else:
comments += f"[{comment.author}]({reddit.config.reddit_url + comment.permalink}): {comment.body}{nl}{nl}"
embed = nextcord.Embed(title="",description = comments,colour = interaction.user.colour)
await interaction.response.send_message(embed = embed,view = Delete_View())```In data.embeds.0.description: Must be 4096 or fewer in length.
Lemme see
your description is way toooo big
SpookyNight @slate swan
WELL HOW CAN I SOLVE THAT?
yea
that way it's a "preview"
also please don't shout, thanks

class Reddit_View(nextcord.ui.View):
def __init__(self,post):
super().__init__()
self.post = post
@nextcord.ui.button(label="Comments",style=nextcord.ButtonStyle.green)
async def comments(self,button:nextcord.ui.Button,interaction:nextcord.Interaction):
submission = await reddit.submission(id = self.post.id)
nl = "\n"
comments = f"**[{submission.title}]({reddit.config.reddit_url + submission.permalink})**{nl}{nl}"
for comment in submission.comments:
if len(comments) < 4096:
comments += f"[{comment.author}]({reddit.config.reddit_url + comment.permalink}): {comment.body}{nl}{nl}"
while len(comments) >= 4093:
comments = comments[:-1]
if len(comments) == 4093:
comments += "..."
embed = nextcord.Embed(title="",description = comments,colour = interaction.user.colour)
await interaction.response.send_message(embed = embed,view = Delete_View())
@nextcord.ui.button(label="๐ฎ",style=nextcord.ButtonStyle.blurple)
async def close(self,button:nextcord.ui.Button,interaction:nextcord.Interaction):
await interaction.message.delete()``` This worked but at the end gave me [dashda](somelink...
and not
@slate swan
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.
what should I write so that it also calculates compound interest
This module provides access to the mathematical functions defined by the C standard.
These functions cannot be used with complex numbers; use the functions of the same name from the cmath module if you require support for complex numbers. The distinction between functions which support complex numbers and those which donโt is made since most users do not want to learn quite as much mathematics as required to understand complex numbers. Receiving an exception instead of a complex result allows earlier detection of the unexpected complex number used as a parameter, so that the programmer can determine how and why it was generated in the first place.
ok
we told u
you should claim a help channel
seems like a bit of a big problem to solve here
help?
that's more of a math problem
let's break it down:
CI = P( 1 + r/100)n - P
P = the amount we start with