#discord-bots
1 messages Β· Page 969 of 1
de-indent process command
!d discord.ext.commands.Bot.listen or just use listen on all events
@listen(name=None)```
A decorator that registers another function as an external event listener. Basically this allows you to listen to multiple events from different places e.g. such as [`on_ready()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_ready "discord.on_ready")
The functions being listened to must be a [coroutine](https://docs.python.org/3/library/asyncio-task.html#coroutine "(in Python v3.10)").
Example...
why listen > event
no need to process on_message events and you can have multiple events i.e on ready
and you can have random function names with the usage of the name kwarg
client doesn't have listen
client doesnt have proccess commands coroutine
Thus he named bot client
π
bro its still a bot instance
no
what
you shouldnt its bad variable naming
yes
Since client is discord.Client and you are using discord.ext.commands.Bot
what should i use to let the bot take the whole line in one arg rather than arg1 arg2 and so on
make the argument a kwarg with an asterisk
You also want, seconds etc?
nope
just want the bot to take the whole user input in a single arg
so it would be ctx, *, argument
k
how can i make a word filter so people can use the command -blacklist test and then it dumps the word test into the blacklist.json or .txt that got created when the command was used?
Heres what i mean:
-blacklist test
The bot creates a blacklist.txt or .json and dumps the word into there
If a user types the word, it deletes the message and says something
If another server uses this command it creates another blacklist1.txt or .json
just use regex
what is that and how to use it
regex is regular expressions and its a standard lib with the name re so it would be imported as re
Regular Expression
ok and how can i make that do what i want? Like how can i master that?
ask @cloud dawn he knows it like completely
its weird how much he knows about itπ³
I'll see you back in 5 years, the art of regex requires meditation in a cave for the first 2 years,
π
Anyhow, if we're just looking at raw words just use the in operator.
!e ```py
text = "regex is regular expressions and its a standard lib with the name re so it would be imported as re"
if "lib" in text:
print("re is a lib yes")
@cloud dawn :white_check_mark: Your eval job has completed with return code 0.
re is a lib yes
he wants a filter so its not convenient
You missed a comma
bro
Smh
!e ```py
text = "regex is regular expressions and its a standard lib with the name re so it would be imported as re"
banned_words = ["lib", "with"]
if any(word for word in banned_words if word in text):
print("ded")
@cloud dawn :white_check_mark: Your eval job has completed with return code 0.
ded
Regex would look for the same thing?
!e
from re import compile
text = "regex is regular expressions and its a standard lib with the name re so it would be imported as re"
regex = compile(r'(lib|with)')
print(regex.sub('', text))
@paper sluice :white_check_mark: Your eval job has completed with return code 0.
regex is regular expressions and its a standard the name re so it would be imported as re
you do know people make variations of the same word right?
is there a way to write a description in an embed without doing description = (description)
fuzzy matching
Re is more used for advanced string manipulation.
like embed.set blablabla
How do I send a video with my bot? like ctx.send(url=url)
I know, then regex but he wasn't talking about that.
Just send a string with the url
bro he wants a filter of bad words
It will embed itself
Yep, still doesn't require regex.
just access the kwarg with an instance of the class
lmao I really was overthinking that
Thank you though bro
Np
Just like okimii is right now, regular python with fuzzy matching is enough.
bro what
embed.set_description(f"id: {member.id}")
why doesnt this work?
its not a method
oh
There is no filter on earth that can catch every variation.
idek how to do that
who said there was? i think youre the one overthinking it lmfao
embed_instance.kwarg = "lol"
i dont literally type kwarg right
!args-kwargs
*args and **kwargs
These special parameters allow functions to take arbitrary amounts of positional and keyword arguments. The names args and kwargs are purely convention, and could be named any other valid variable name. The special functionality comes from the single and double asterisks (*). If both are used in a function signature, *args must appear before **kwargs.
Single asterisk
*args will ingest an arbitrary amount of positional arguments, and store it in a tuple. If there are parameters after *args in the parameter list with no default value, they will become required keyword arguments by default.
Double asterisk
**kwargs will ingest an arbitrary amount of keyword arguments, and store it in a dictionary. There can be no additional parameters after **kwargs in the parameter list.
Use cases
β’ Decorators (see !tags decorators)
β’ Inheritance (overriding methods)
β’ Future proofing (in the case of the first two bullet points, if the parameters change, your code won't break)
β’ Flexibility (writing functions that behave like dict() or print())
See !tags positional-keyword for information about positional and keyword arguments
You can name them anything but it's called kwarg so everyone knows what you are referring to.
bro
no
kwargs is every keyword argument.
theyre arguments in the parameters.
!tags positional-keyword
Positional vs. Keyword arguments
Functions can take two different kinds of arguments. A positional argument is just the object itself. A keyword argument is a name assigned to an object.
Example
>>> print('Hello', 'world!', sep=', ')
Hello, world!
The first two strings 'Hello' and world!' are positional arguments.
The sep=', ' is a keyword argument.
Note
A keyword argument can be passed positionally in some cases.
def sum(a, b=1):
return a + b
sum(1, b=5)
sum(1, 5) # same as above
Somtimes this is forced, in the case of the pow() function.
The reverse is also true:
>>> def foo(a, b):
... print(a, b)
...
>>> foo(a=1, b=2)
1 2
>>> foo(b=1, a=2)
2 1
More info
β’ Keyword only arguments
β’ Positional only arguments
β’ !tags param-arg (Parameters vs. Arguments)
!e ```py
def test(**kwargs):
print(kwargs)
test(a=1, b=2)
@cloud dawn :white_check_mark: Your eval job has completed with return code 0.
{'a': 1, 'b': 2}
didnt i await get_multiplier
Try putting more () around the function so the closing bracket is before the [0]
Yes but the await in the bracket
oh
Easier to just use multiple lines
The await executes the whole statement and getting item is another statement which is non async so yeah you need to put the statement you actually want to await into the brackets to separate it from item getting
Sorry for poor explanation π©
idk how to describe it but i want my bot to check if theres a file with the guild id as its name and if yes it should look if the user wrote a blacklisted word
!d os.path.exists
os.path.exists(path)```
Return `True` if *path* refers to an existing path or an open file descriptor. Returns `False` for broken symbolic links. On some platforms, this function may return `False` if permission is not granted to execute [`os.stat()`](https://docs.python.org/3/library/os.html#os.stat "os.stat") on the requested file, even if the *path* physically exists.
Changed in version 3.3: *path* can now be an integer: `True` is returned if it is an open file descriptor, `False` otherwise.
Changed in version 3.6: Accepts a [path-like object](https://docs.python.org/3/glossary.html#term-path-like-object).
And yeah don't use txt files for data storage
why not?
why is it not running the whole thing
Because that's cringe bad storage way
i get it π
The same problem may have happened at ur if statement
Read this @slate swan
it prints the "A"
tho
The second one
what does /n do
?
if await get_coins(ctx)[0]
oh lemme try
So change that how u changed the one before
how do i move text down a line
New line?
yeah
\n
it doesnt update db nor send success message but it now prints calculation
where do i put it
like if my description was too long
and i wanted to move it down a line
description = 'ashdiasdasoidiwq89udewjufe82uwd9j32iewh9ye0jwdiofjdwif8ew'
where do i put /n @torn sail
Put it where u wanna break the line
Yeah
Iβm not sure. Iβve have problems with that lib too
'ashdiasdasoidiwq89udewjufe' /n '82uwd9j32iewh9ye0jwdiofjdwif8ew'
ooh yea i just realised 1 element tuples need a trailing comma
Ohh yeah
like this?
AYEE
Nice
\ not /
Yw
# server icon command
@client.command()
async def servericon(ctx):
embed = discord.Embed(colour = 0x36393F)
embed.add_field(name = f"{guild.name}'s icon", value = f'**[download]({guild.icon_url})**')
embed.set_image(url = ctx.guild.icon_url)
await ctx.send(embed = embed)
why doesnt this work
oh i havent
oh
any help?
colour not coloyr
oh yea
@client.command()
async def servericon(ctx, guild : discord.Guild):
embed = discord.Embed(colour = 0x36393F)
embed.add_field(name = f"{guild.name}'s icon", value = f'**[download]({guild.icon_url})**')
embed.set_image(url = ctx.guild.icon_url)
await ctx.send(embed = embed)
this doesnt work
anybody know why?
does anyone know how to create slash command group in nextcord?
value=ctx.guild.icon
if the guild has no guild icon. you'll get an error
ohh
@client.command()
async def servericon(ctx, guild):
embed = discord.Embed(colour = 0x36393F)
embed.add_field(name = f"{guild.name}'s icon", value = f'**[download]({guild.icon_url})**')
embed.set_image(url = ctx.guild.icon)
await ctx.send(embed = embed)
no still doesnt work
@client.command()
async def servericon(ctx):
em = discord.Embed(title="Guild Icon", color=0x36393F)
em.set_image(url=ctx.guild.icon)
await ctx.send(embed=em)
why did you pass guild in the parameter
thx
oke
is there no way to get the bot to say the server name
without putting it in the code?
like {guild.name}
or something
@hazy oxide
can someone help me fix that my bot does not scan every guild if they have a blacklisted word?
so it only checks the servers that already have a blacklisted word?
f"{ctx.guild.name}'s icon"
ty
this doesnt even work
Try @bot.listen()
Why
Try not using embed
:I
doesnt put anything in the channel, doesnt give any errors
nothing happens pretty much
Did you restart your bot after you added the code?
yes
What library do you use?
And share your full code of your main file
the entire code?
Yeah
all my commands?
Something else could be fucking up your command
Yeah
ok
Hey @umbral night!
You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.
oh
!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.
Looks like it doesnt work it
Looks like it isn't indented properly
There is no file named ctx.guild.id.txt
Or maybe you want to check in every server by putting server name
oh
It looks like you use 2 spaces for each indent in everywhere else
For the guild icon code it's 4 spaces
what
Which is the recommended amount of spaces
but then it will just say "No such file or directory: 'guild name.txt'" i think
4?
Is that a file that contains blacklisted words?
@client.command()
async def servericon(ctx):
em = discord.Embed(title="Guild Icon", color=0x36393F)
em.set_image(url=ctx.guild.icon)
await ctx.send(embed=em)```
wonder why π€
Probably your ide
basically yes, if the server uses the command -blacklist word it creates a new file with the server id and the blacklisted words inside and the bot should check if a user in that guild said a blacklisted word
Just unindent it and indent it back
Your ide should indent it normally
Which is 2
ohh
Add a print statement inside the command
idk what that is
And invoke the command
π
π
I suggest learning python first before tackling on an advance lib
:I
You don't even know what a print statement is so start at the beginning
@client.command()
async def servericon(ctx):
embed = discord.Embed(title = f"{ctx.guild.name}'s icon", color=0x36393F)
embed.set_image(url=ctx.guild.icon)
await ctx.send(embed = embed)
it should work
But it doesn't
oh u mean like print(x)
So something is preventing it to work
Yes
It's called a print statement
Now add it to the command
await print(embed)
π
No
what
Print anything
We just need to see if the command even runs
you can try url=icon instead of url=ctx.guild.icon, atleast thats what i have
other stuff works fine
Check your console
i dont see how that'd work but ok
That will not work
He doesn't have icon defined
well for me it works
You do
Because you have it defined
ctx.guild.icon works fine
replit
Self host
i cant self host
π i dont have money
Refresh replit
i only have 1 phone
Replit has a bug where you're writing ghost code but replit doesn't save it
Use it
damn i just got rate limited

and i use a chromebook, i cant even get vsc
Okimii help
A chromebook can get vsc
||wut||
I use my chromebook to code
dont i have to download linux
what!
ok teach me how
No
Depends do you own it
Do you own the chromebook or is a school letting you use it
i own it
Okay
hi
my bot has strange http error when I want to use any command containing embed, how to fix it?
show the error
I'm not at home, can I send you later on dm?
sure
Invalid form of body?
I am not able to check it now I am away from home I will send you later sorry
Okay
why is that not possible?
its all in a directory but it cant find it because of that
use its opposite
/
thanks
π
Why does my bot spam this all the time? I have a return statement on the bottom?
When Iβm using my sound bot it says ffmpeg not found when Iβve clearly installed it
I mean, are you sending the webhook from a command or what?
code
uh well, you could just get the channel id straightaway
ctx.channel.id
Hello ducky
show the command
i just found out the bot also spams to any message writen
the screenshot isnt pleasant to look at, use a pasting service
!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.
Hello ashley
any idea why this doesnt work
i have debugged it in the terminal
it wont run after the execution line of my database
!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.
i was showing the terminal but i already got answer
oh ok sure
Why does my bot spam to any message if i embeded something but if its not embeded it doesnt spam?
How can I convert this playing in a vc but not using ffmpeg
hey skev
What
There are people who use them
it is always necessary if you are building an application for production
there are other factors of why they are used
k ty
it is easier to export an entirely virtual env instead of recreate it on an external machine
Yo is there away to store more than 1 channel in a json file
wdym
json is not a storage method, json is used to store javascript object as text, btw you can store an array of object:
{"channels":[
{"id":"#id", "name":"name"},
{"id":"#id", "name":"name"}
]}
whats the best way to organize lots of cogs?
wdym?
directory structure
The best practice is to have all cogs under a single folder so you can import them with a for loop iterating through the file list in that folder
then this folder becomes huge
depends
i could have folders too
importing them will be a messy
because folders can be loaded as modules if they have __init__.py
so i could create a folder for each category of commands
cogs folder should not have an init module, I use my cogs to categorize commands and events
why
then my other stuff like checks, tasks and others will be in another folder, separated by category
because is the best practice
an example
yup this is good
but its the same what i mean
Does anyone have an invite tracker source code for me?
the structure of my biggest project looks like this:
MyProjectName:
data: #Folders where data storage method are storage
db: #database with inside a sql file with commons query script that can be launched
other_storage_method:
lib: #The folder which contains the whole project
bot: #Here my bot instance is storage and in it there are some utils script like custom checks or tasks
__init__.py #Instance of the bot
AdminChecks: #Folder for admin custom checks
UserChecks: #Folder for user custom checks
so_goes_on:
cogs: #Cogs folder
db: #Folder which contains database script in python
__init__.py #inizialize the db
db.py #db script
Others_folders_where_common_script_and_classes_are_stored:
launcher.py #the script which runs the bot
i did it once, never test it btw
https://pastebin.com/raM9RCC1
This is the cogs where i code the invite tracker
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
you can ignore the commands the main things which does the trick are the events
bro why are these slash commands not syncing, it's been like 5 houes
most probably due to API issue or because your bot is rate limited
try to specify the guild_id where you initialize the slash command an test it
yeah, i do that. nothing is wrong. its not syncing.
then the problem is not yours xD
import requests
from io import BytesIO
url = f'https://some-cool-api.herokuapp.com/youtube_music?query=k391+ignite'
response = requests.get(url)
data = BytesIO(response.content))
_bot.get_channel(942663766745710653).send(files=data)```
What's the issue here?
neither is it discords
there's no problem anywhere, don't know why it's not working
Anyone please....
you got to await the send method
await (bot.get_channel()).send()```
Thx!!
It ain't inside async function
well you are pretty much out of options then or use http methods with requests to post messages or smth
I see that as irrelevant
it is
The issue is never with sending msgs
well, then tell me what the issue is
Eof
and files should be a list
well
with open('logs.json', 'r') as f:
log_channels = json.load(f)
@client.command(name="logchannel", aliases=["setlog","setlogchannel"],description="Sets the log channel for your server logs")
@commands.has_permissions(administrator = True)
async def modlog(ctx, channel = None):
log_channels[str(ctx.guild.id)] = channel.split()
with open('logs.json', 'w') as f:
json.dump(logs.json, f)
await ctx.send(f'Log channel set to {channel}')
``` Why is logs not defined?
i mean, bytes object in a list
"logs.json" has to be a string
!d discord.TextChannel.send
ah
await send(content=None, *, tts=False, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, ...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Sends a message to the destination with the content given.
The content must be a type that can convert to a string through `str(content)`. If the content is set to `None` (the default), then the `embed` parameter must be provided.
To upload a single file, the `file` parameter should be used with a single [`File`](https://discordpy.readthedocs.io/en/master/api.html#discord.File "discord.File") object. To upload multiple files, the `files` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.10)") of [`File`](https://discordpy.readthedocs.io/en/master/api.html#discord.File "discord.File") objects. **Specifying both parameters will lead to an exception**.
To upload a single embed, the `embed` parameter should be used with a single [`Embed`](https://discordpy.readthedocs.io/en/master/api.html#discord.Embed "discord.Embed") object. To upload multiple embeds, the `embeds` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.10)") of [`Embed`](https://discordpy.readthedocs.io/en/master/api.html#discord.Embed "discord.Embed") objects. **Specifying both parameters will lead to an exception**.
I don't think it's important to be in a list
lemme check
Hm
json.dump("logs.json", f)
``` like that?
nvm, readthedocs never gonna open on my phone ever again
I guess no
what is the response from the api?
An audio
dump, log_channels, not a string
uhhh, weird api, but well, goodluck then
Wait so what needs to be a string
you dont dump strings into a json file, instead you put dictionaries
is there a package for forms?
but iirc, that works only with js
why-
What only works with js?
no not that actually
audio player with spotify api, or am I insane
You are insane
Language totally doesn't matter
egirl hmm
class discord.ui.Modal(*, title=..., timeout=None, custom_id=...)```
Represents a UI modal.
This object must be inherited to create a modal popup window within discord.
New in version 2.0.
Examples...
Ah it's new in 2.0

Don't. It's against ToS
with open('log_channels.json', 'r') as f:
log_channels = json.load(f)
@commands.command(name="kick", description="Kicks a user from the server")
@commands.has_permissions(kick_members=True)
async def kick(self, ctx, member: discord.Member, *, reason=None):
if member == None:
await ctx.send("Please mention a user")
else:
await ctx.guild.kick(user=member, reason=reason)
channel_id = log_channels.get(str(ctx.guild.id), '0')
channel = client.get_channel(channel_id)
embed = discord.Embed(title=f"{ctx.author.name} kicked: {member.name}", description=reason)
await channel.send(embed=embed)
await ctx.send(f'Kicked **{member.name}** for **{reason}**')
``` How do I make it so log_channels is defined, it now says it isn't. Is it indentation?
How?

self.log_channels = json.load(f)
And then ```py
channel_id = self.log_channels.get(str(ctx.guild.id), '0')
No
why casting a string on the guild id? 
Okay
get takes int
Ah yeah
You can't set an int as key
In a JSON
Wait so leave the str or?
channel_id = log_channels.get(str(ctx.guild.id)
``` Just like that then
Yea leave it. But don't forget to turn it to int while using get_channel
Yups
Aight let me see
channel = self.client.get_channel(channel_id)
``` It says that it's invalid syntax
Is it in cog
Yes
If so first arg of the function must he self
I know
U prolly forgot self as the first arg
What do you mean by that
I mean
async def kick(...):
await some_func()
async def some_func(...):
# do stuff```
Hm?
Erm pretty sure I don't have that
Ok could you show full kick command
Sure
with open('log_channels.json', 'r') as f:
self.log_channels = json.load(f)
@commands.command(name="kick", description="Kicks a user from the server")
@commands.has_permissions(kick_members=True)
async def kick(self, ctx, member: discord.Member, *, reason=None):
if member == None:
await ctx.send("Please mention a user")
else:
await ctx.guild.kick(user=member, reason=reason)
channel_id = log_channels.get(str(ctx.guild.id))
channel = self.client.get_channel(channel_id)
embed = discord.Embed(title=f"{ctx.author.name} kicked: {member.name}", description=reason)
await channel.send(embed=embed)
await ctx.send(f'Kicked **{member.name}** for **{reason}**')
Weird
It's cog.
It's still against ToS to stream music via the raw API
I don't have that?
Mhm, still against ToS
You need to own the music
Depends what service you use
use ctx.bot
I use client though?
Pretty sure soundcloud allows streaming audio
Still
And where on what line
Instead of self.client, use ctx.bot
Let me see
That thing is rarely used
Same error
Self not defined?
Nameerror self is not defined
Could you give full traceback
Sure
Traceback (most recent call last):
File "/home/runner/bbbb/venv/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 606, in _load_from_module_spec
spec.loader.exec_module(lib)
File "<frozen importlib._bootstrap_external>", line 843, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "/home/runner/bbbb/cogs/moderation.py", line 34, in <module>
class Moderation(commands.Cog):
File "/home/runner/bbbb/cogs/moderation.py", line 67, in Moderation
self.log_channels = json.load(f)
NameError: name 'self' is not defined
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "main.py", line 58, in <module>
client.load_extension(f'cogs.{filename[:-3]}')
File "/home/runner/bbbb/venv/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 678, in load_extension
self._load_from_module_spec(spec, name)
File "/home/runner/bbbb/venv/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 609, in _load_from_module_spec
raise errors.ExtensionFailed(key, e) from e
discord.ext.commands.errors.ExtensionFailed: Extension 'cogs.moderation' raised an error: NameError: name 'self' is not defined
It's in different function lmao
Huh
Self is not defined in static load or smth
Whats that
You need to define it in _init_
I mean init function
oh
class MyClass:
def __init__(self, bot):
self.bot = bot```
class Moderation(commands.Cog):
def __init__(self, client):
self.client = client
I got that
Alright
class Moderation(commands.Cog):
def __init__(self, client):
self.client = client
with open('log_channels.json', 'r') as f:
self.log_channels = json.load(f)
``` like that?
Yes but indent the with content
the last 2 lines?
One
the with open as the same indent as def?
with create_thing() as something:
do_stuff_with(something)```
class Moderation(commands.Cog):
def __init__(self, client):
self.client = client
with open('log_channels.json', 'r') as f:
self.log_channels = json.load(f)
``` that?
Yes
No wtf
Or can I use self.client
self.client
@vale wing
Let me see if it works
Both self.client and ctx.bot will work but self.client is more suitable
log_channels is not defined
self.log_channels
Yeah I thought of that
Ignoring exception in on_command_error
Traceback (most recent call last):
File "/home/runner/bbbb/venv/lib/python3.8/site-packages/discord/client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "main.py", line 85, in on_command_error
raise error
File "/home/runner/bbbb/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "/home/runner/bbbb/cogs/moderation.py", line 80, in kick
channel = self.client.get_channel(channel_id)
File "/home/runner/bbbb/venv/lib/python3.8/site-packages/discord/client.py", line 793, in get_channel
return self._connection.get_channel(id)
File "/home/runner/bbbb/venv/lib/python3.8/site-packages/discord/state.py", line 1118, in get_channel
pm = self._get_private_channel(id)
File "/home/runner/bbbb/venv/lib/python3.8/site-packages/discord/state.py", line 329, in _get_private_channel
value = self._private_channels[channel_id]
TypeError: unhashable type: 'list'
@vale wing Got any clue
Or anyone else
your channel_id variable is somehow a list
Erm yeah, got any idea on how I could fix that?
!e
code
!e
dct = {"abc": 1, "cdb": [1, 2]}
print(f"{dct['abc']} {dct['cdb']}")
@placid skiff :white_check_mark: Your eval job has completed with return code 0.
1 [1, 2]
probably he has something like this
Is there a way to stop discord.ui.button from timing out
help ```py
ImportError: cannot import name 'format_dt' from 'discord.utils'
just set the timeout to None
!json
When using JSON, you might run into the following error:
JSONDecodeError: Expecting value: line 1 column 1 (char 0)
This error could have appeared because you just created the JSON file and there is nothing in it at the moment.
Whilst having empty data is no problem, the file itself may never be completely empty.
You most likely wanted to structure your JSON as a dictionary. To do this, edit your empty JSON file so that it instead contains {}.
Different data types are also supported. If you wish to read more on these, please refer to this article.
@placid skiff i wrote this thing https://paste.pythondiscord.com/uquqezahax
it will yield every package (folder with __init__.py), every module (file.py) and the same from all subdirectories
packages ofc are excluded from subdirectories because they are already loaded
How to fix this error?
cogs/
general/
ping.py
google/
__init__.py # loads what needed itself
translate/
api.py
__init__.py
looks like an invisible character in the string
How to remove it
In python, the \ character is an escape character
u didnt escape backslashes
You need to escape the escape character
or use literal string r"my\path"
far more readable
here
I've made a ban command for my bot, however I want it to reply with an error if a valid user or id isnt passed through. It doesnt seem to work when I do it like this, and I'm not sure what other way to do it
async def ban(self, ctx, member: discord.Member, *, reason=None):
if reason==None:
reason=" No reason provided"
embed = discord.Embed(title=':white_check_mark: Successfully Banned!', description=f'{member.name}#{member.discriminator} has been Banned. Reason: `{reason}`.', color=0xff0000)
embed.set_thumbnail(url=member.avatar)
embed.set_footer(text="Requested by: {}".format(ctx.author.display_name), icon_url=ctx.author.avatar)
await ctx.send(embed=embed)
await ctx.guild.ban(member)
if member==None: #tried if member()==None: too
embed = discord.Embed(title=':no_entry: Error banning member!', description='Please provide a valid mention/ID!', color=0xff0000)
embed.set_footer(text="Requested by: {}".format(ctx.author.display_name), icon_url=ctx.author.avatar)
await ctx.reply(embed=embed)
does anyone know how to create slash command group in nextcord?
how to get list banned on guild with nextcord?
await bans()```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Retrieves all the users that are banned from the guild as a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.10)") of [`BanEntry`](https://nextcord.readthedocs.io/en/latest/api.html#nextcord.BanEntry "nextcord.BanEntry").
You must have the [`ban_members`](https://nextcord.readthedocs.io/en/latest/api.html#nextcord.Permissions.ban_members "nextcord.Permissions.ban_members") permission to get this information.
await ctx.guild.bans()
Asking this here since my db is for a discord bot, Does anyone mind sanity checking my SQL for me? I've sent a msg in #databases with a link to a pastebin of my SQL and a few sentences of what I am trying to achieve with it, do let me know if you have any questions.
is there a way to make a hard space/nbsp in discord embed
don't take my answer as your final answer but I don't think there's a way to do that. What are you trying to do with your embed?
File "/home/ditttt/discord_bot/dittttbot/data/ban.py", line 366, in unban_
bannnedUsers = await interaction.guild.bans()
TypeError: object BanIterator can't be used in 'await' expression
The above exception was the direct cause of the following exception:
nextcord.errors.ApplicationInvokeError: Command raised an exception: TypeError: object BanIterator can't be used in 'await' expression``` @hazy oxide @slate swan
Create a variable first
class Help(commands.Cog):
def __init__(self, bot):
self.bot = bot
class HelpModal(Modal):
def __init__(self) -> None:
super().__init__("Name")```
discord.app_commands.errors.CommandInvokeError: Command 'help' raised an exception: TypeError: __init__() takes 1 positional argument but 2 were given
I think the problem is class inside class but how do Modal with cog without class inside class
i need a avatar command for hikari-lightbulb which shows a targets avatar
is it possible to use commands.Cog.listener() to detect commands
Iirc yes
how? on_command doesn't seem to be a thing
What variable?
You can use on_message and detect a command
Also why would you
you would need a member/user option for that py @bot.command @lightbulb.option("member", "member to show avatar", type=hikari.User) @lightbulb.command("avatar", "desc") @lightbulb.implements(...) async def avatar( ctx): avatar = ctx.options.member.avatar_url
Ignoring exception in on_command_error
Traceback (most recent call last):
File "/home/runner/bbbb/venv/lib/python3.8/site-packages/discord/client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "main.py", line 85, in on_command_error
raise error
File "/home/runner/bbbb/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "/home/runner/bbbb/cogs/moderation.py", line 80, in kick
channel = self.client.get_channel(channel_id)
File "/home/runner/bbbb/venv/lib/python3.8/site-packages/discord/client.py", line 793, in get_channel
return self._connection.get_channel(id)
File "/home/runner/bbbb/venv/lib/python3.8/site-packages/discord/state.py", line 1118, in get_channel
pm = self._get_private_channel(id)
File "/home/runner/bbbb/venv/lib/python3.8/site-packages/discord/state.py", line 329, in _get_private_channel
value = self._private_channels[channel_id]
TypeError: unhashable type: 'list'
logging
Couldn't you just have a logging code in the command itself
Any idea anyone or would you need more info
also an idea
Okay
Well just use an on_message and get context from the message itself and check if ctx.valid is true
I don't know or remember if you can check which command is triggering
I'll just take a quick look at the docs
Hello sarth
!d discord.ext.commands.Context.command will return a command if its a command, else None or maybe a attr error
The command that is being invoked currently.
heya
thanks
lemme check the src
(although i think i should just put the logger in the command)
Anyone 
are you like trying to do something every time a command is used?
you're passing channel_id into self._private_channels
Me?
implementing logging
yeah
So what do I do to fix that?
oh and channel_id is a list
Yeah I think that's the issue
In main or do I fix that in my cog?
!d discord.ext.commands.on_command_completion
No documentation found for the requested symbol.
wait that's a thing?
yep
huh
@shrewd kraken Is the issue here in my main file?
with open('log_channels.json', 'r') as f:
log_channels = json.load(f)
@client.command()
@commands.has_permissions(administrator = True)
async def modlog(ctx, channel = None):
log_channels[str(ctx.guild.id)] = channel.split()
with open('log_channels.json', 'w') as f:
json.dump(log_channels, f)
await ctx.send(f'Mod log set to {channel}')
you can use the 1st one or the 2nd one
in kick
the 2nd one gets called only when the command works without any error
the error is in the kick cmd
Okay
can you show the code of the kick cmd?
thanks
with open('log_channels.json', 'r') as f:
self.log_channels = json.load(f)
@commands.command(name="kick", description="Kicks a user from the server")
@commands.has_permissions(kick_members=True)
async def kick(self, ctx, member: discord.Member, *, reason=None):
if member == None:
await ctx.send("Please mention a user")
else:
await ctx.guild.kick(user=member, reason=reason)
channel_id = self.log_channels.get(str(ctx.guild.id))
channel = self.client.get_channel(channel_id)
embed = discord.Embed(title=f"{ctx.author.name} kicked: {member.name}", description=reason)
await channel.send(embed=embed)
await ctx.send(f'Kicked **{member.name}** for **{reason}**')
can i see log_channels.json?
Sure
it needs the bot inside the server
{"873510385871904838": ["[#962982270204018708](/guild/267624335836053506/channel/962982270204018708/)"]}
ah
that's why
try
channel_id = self.log_channels.get(str(ctx.guild.id))[0]```
and also that's not a channel id, the channel id is 962982270204018708
uhm i think that command_completion is called when the whole command finished. For example if your command waits for an event then the command will not finished until that event is resolved
I had that but they told me to remove it
why?
How do I fix that for when I do it in a new server that it wont do the <# and stuff
{"873510385871904838": ["962982270204018708"]}
``` like that?
yep
I mean it put a <#> in the json
you're saving an id as an array
Yeah I see, where do I fix that?
An event that is called when a command has completed its invocation.
This event is called only if the command succeeded, i.e. all checks have passed and the user input it correctly.
thats what the docs say.
when you save the data (?)
log_channels[str(ctx.guild.id)] = channel.split()
``` Is it because of the str?
when you get the channel you can use string.split("<#>")
command succeeded the command succeeded after the whole command function is finished
if you wait for an event in the function of the command that it will not be finished until that event is resolved
thats what i said
when the command works without any error
Should I do that?
the complete callback comes under its functioning
And that's in the kick command then?
channel = self.client.get_channel(channel_id)
``` here?
Wait so this is fine right
with open('log_channels.json', 'r') as f:
log_channels = json.load(f)
@client.command(name="setlog",description="Sets a custom log channel for your server",aliases="setlogchannel")
@commands.has_permissions(administrator = True)
async def modlog(ctx, channel = None):
log_channels[str(ctx.guild.id)] = channel.split()
with open('log_channels.json', 'w') as f:
json.dump(log_channels, f)
await ctx.send(f'Mod log set to {channel}')
split returns a list, strip should be used for stripping substring
Hello blvck
!e
str1 = "123_abc"
str2 = "456_dbe"
print(str1.split('_'))
print(str2.strip('_'))
@placid skiff :white_check_mark: Your eval job has completed with return code 0.
001 | ['123', 'abc']
002 | 456_dbe
Is this fine?
well this is drunk 
Ignoring exception in on_command_error
Traceback (most recent call last):
File "/home/runner/bbbb/venv/lib/python3.8/site-packages/discord/client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "main.py", line 113, in on_command_error
raise error
File "/home/runner/bbbb/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "/home/runner/bbbb/cogs/moderation.py", line 83, in kick
await channel.send(embed=embed)
AttributeError: 'NoneType' object has no attribute 'send'
``` this is the error I'm getting now
@commands.command(name="kick", description="Kicks a user from the server")
@commands.has_permissions(kick_members=True)
async def kick(self, ctx, member: discord.Member, *, reason=None):
if member == None:
await ctx.send("Please mention a user")
else:
await ctx.guild.kick(user=member, reason=reason)
channel_id = self.log_channels.get(str(ctx.guild.id))[0]
channel = self.client.get_channel(channel_id)
embed = discord.Embed(title=f"{ctx.author.name} kicked: {member.name}", description=reason)
await channel.send(embed=embed)
await ctx.send(f'Kicked **{member.name}** for **{reason}**')
``` Kick command
strip removes leading and trailing characters, of course what you did wouldnβt work with strip
Anyone any idea on how to fix it
OOH, could it be possible u have an interaction object instead of a ctx object???
if that's the case, ctx.response.send_message("your message here") should work
i could be terribly wrong tho
ples lmk if it works
is it possible for the bot to change a channel name
the channel is already created
await edit(*, reason=None, **options)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Edits the channel.
You must have the [`manage_channels`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.manage_channels "discord.Permissions.manage_channels") permission to use this.
Changed in version 1.3: The `overwrites` keyword-only parameter was added.
Changed in version 1.4: The `type` keyword-only parameter was added.
Changed in version 2.0: Edits are no longer in-place, the newly edited channel is returned instead...
wait i wanna do it like
when the bot is ready it should set the name of the channel to total number of guilds it is in
don't do it in on_ready
Use tasks
then?
Use this
Use tasks as saad said
discord.ext.tasks.loop(*, seconds=..., minutes=..., hours=..., time=..., count=None, reconnect=True)```
A decorator that schedules a task in the background for you with optional reconnect logic. The decorator returns a [`Loop`](https://discordpy.readthedocs.io/en/master/ext/tasks/index.html#discord.ext.tasks.Loop "discord.ext.tasks.Loop").
Finally-
@slate swan you're looking for this
Please don't use ableist language. Thanks π
dw

!d discord.Embed.set_thumbnail
set_thumbnail(*, url)```
Sets the thumbnail for the embed content.
This function returns the class instance to allow for fluent-style chaining.
Changed in version 1.4: Passing `None` removes the thumbnail.
does it set it on the top right tho?
yes thats the thumbnail
So I have an embed with 4 fields, how would I make it so field 1 and 2 are inline with each other and 3 and 4 are inline with each other but 1 and 2 are not inline with 3 and 4?
tryna beautify it xd
wanna make the value of the field to be in center
Idk tbh but try to make them in description =?
well all fields go from 3 to 3 if inlined
not sure
if message.content.startswith('!connect'):
embedVar = discord.Embed(title='`How to connect:`', description='`1.`Start **__FiveM.exe__** \n`2.`Press **__F8__** \n`3.`Copy and paste **__connect(ip)__**', color=0xf70223)
file = discord.File("Desktop", filename="dababy.jfif")
await message.channel.send(embed=embedVar , file)
Im also trying to make a mute/timeout command, how would I define the max values for days, seconds etc:
async def mute(self, ctx, member: discord.Member, reason=None, days=?:
ty for your help
i used ```py
await channel12.edit(name=(f"{len(client.guilds)}"))
and it works
yeah I don't think there's a way to do that
is it possible to get a variable from another file?
i have one variable BOT_NAME in another file
why f"{len(client.guilds)}"
and wanna use it in my main file
wym?
when you could just do str(len(client.guilds)), or even just len(client.guilds) would work.
is that just your bot name?
but it still works
yes
just using it for testing
just do bot.user.name...
and if you want to use a function/variable from other file
import it
i mean if i removed the embed variable from my main file to another file
will i be able to use it?
k
# otherfile.py
my_variable = "here"```
```py
#mainfile.py
from otherfile import my_variable``` basic python imports
Anyone have a good bot idea
Hey @slate swan!
You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.
bingo bot
Whats bingo
the classic bingo game?
and how would that work
google it
what's that?
no thanks 
old game which is pretty cool


title="Test",
escription="If you have any questions or concerns create a new ticket by clicking on the emoji below this message.",
color=0xf7fcfd)
embed.set_thumbnail(
url="https://cdn.discordapp.com/attachments/771635939700768769/773121323341578250/external-content.duckduckgo.com.png") \
if message.content.startswith('!test'):
await message.channel.send(embed)```
embed=embed :)
aa
u need to pass it as a kwareg
why won't my slash commands sync? it's been doing this since for days. bot has been up for hours and they still won't sync
@paper sluice thanks
that can depend on the library you're using as synchronizing can be either automatic or manually triggered, with the latter being a more preferable option
using nextcord
also i tried to use another url but it doesn't work
can i do that if the bot is in a server and the server's id is in another file (for example test.txt) then none of the commands should work for that particular server
How can i cheeck py if "!" in nick.content: embed=discord.Embed(title="**Nie moΕΌesz posiadaΔ takiego nicku!**", color=0xff0000) embed.set_footer(text=f"Wykonano przez {ctx.author}") await ctx.send(embed=embed)
hmmm
beacuse i have error here
if "!" in nick.content:
AttributeError: 'str' object has no attribute 'content'
i did mine like async def mute(self, ctx, years: int=0, months: int=0, days: int=1, hours: int=0, minutes: int=0, *, reason: str='None') and just passed those onto a time delta
what object is nick?
any errors?
@bot.command()
async def reg(ctx, nick):```
No
hey, can you typehint values as a timedelta?
send ur code again
lemme find out
.
time?
anyone know where to get some creative commons pixel art playing cards
i caaaant bring myself to draw 52 cards
very specific, kinda sus
you wanna play poker over discord?
adding blackjack to my bot
what is the output?
whats output
i havent used nextcord before so im not sure how they handle it, but from what i can figure out from the docs you might be able to trigger the synchronization yourself using the Client.rollout_application_commands() method
what happens when you run that
a
like this ^^ what are you getting now
wow you are a helper
guess my job here is done
so whats wrong?
embed.set_image(discord.File)
so for example embed.set_image(discord.File(r'fp'))
am i gonna have to code something just to draw these cards for me
.
take a picture of real cards, crop 'em, pixelate and you're finished
true true
you are linking a question with no context
force_global=True
for 52 cards... the amount of clean up to get them to a resolution of 50x70
i think this fixes my problem
you have a better solution?
yes
can i do that if the bot is in a server and the server's id is in another file (for example test.txt) then none of the commands should work for that particular server
im gonna make the base card and then get pillow to draw with a nice font the numbers and then maybe paste some game assets as the hearts and whatever
neto
do, what
im asking for context to question to help you
although i have no idea if this is gonna be any faster 
explaining again
ig this is what comes up when i search up pixelated deck of cards creative commons
(lancer theme intensifies)
im saying that if the server my bot is in and its name/id is in particular file then no command should work for the guild
aka blacklist
yes
if you can read the file, yes
Yeah thatβs easy
k
h o w
In your on message, if the message is from a certain guild, then do a blank return
Nope I just use ctx
!e import json
json.dumps(["hello", "world"])
@quaint epoch :warning: Your eval job has completed with return code 0.
[No output]
k ty
okay yeah, just store the list in a file/db, read and you're good to go
lemme give you and example
ok
guild id: 696969696969 is blacklisted
sus but ok
so, we put that id in a list in a json file
json file looks like - ["696969696969"]
now we do blacklist = json.loads(file)
no wait
just tell me if there is single line code to do this
just like i said in the code block
yes but do you like esoteric?
your loss
kden'
gimme a sec
sec
π
import json
is_blacklisted = lambda id: any(str(i) in str(id) for i in json.load(open('blacklisted.json', 'r')))```
it expects 'blacklisted.json' to be a list of strings
i.e ["69", "420", "666"]
Traceback (most recent call last):
File "/home/runner/bbbb/venv/lib/python3.8/site-packages/discord/client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "main.py", line 113, in on_command_error
raise error
File "/home/runner/bbbb/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "/home/runner/bbbb/cogs/moderation.py", line 83, in kick
await channel.send(embed=embed)
AttributeError: 'NoneType' object has no attribute 'send'
``` Why does this error?
@commands.command(name="kick", description="Kicks a user from the server")
@commands.has_permissions(kick_members=True)
async def kick(self, ctx, member: discord.Member, *, reason=None):
if member == None:
await ctx.send("Please mention a user")
else:
await ctx.guild.kick(user=member, reason=reason)
channel_id = self.log_channels.get(str(ctx.guild.id))[0]
channel = self.client.get_channel(channel_id)
embed = discord.Embed(title=f"{ctx.author.name} kicked: {member.name}", description=reason)
await channel.send(embed=embed)
await ctx.send(f'Kicked **{member.name}** for **{reason}**')
read the error
i think u need to have members and guilds intents on to use get_channel
I did, but got no clue why it errors
channel, isn't a channel object
Got them all on
it's a no return
oh uea
So how do I fix that, don't fully get it.
discord.Object(id=...)
Hm?
print(channel_id, type(channel_id))) and tell me how that goes
Sure
the id might not have been valid
Does it matter where?
before the channel.send
{"873510385871904838": ["962982270204018708"]}
``` Does this maybe need to have <#> ?
no, just print out in the code
alr
don't snow me the json file
Relax
heheheheh, snow
Why do you save the id in a list?
I don't know why it did that
Are they supposed to be multiple?
yup, you got the wrong type
Guild id and channel id
discord expected an int, and you got a string in a list
channel_id = self.log_channels.get(str(ctx.guild.id))[0]
``` so change the str to a int there?
nope
oh
channel = self.client.get_channel(int(channel_id))
you probably did py import tracemalloc tracemalloc.start()?
uh no
o
well try this anyway
when you fetched the channel, it expected an int for the id, you passed a string
so it was a convert
50% of the way to making the code draw it for me
why does the Q look like a O
god dammit
slowly gettin there, just gotta add some sort of image which is gonna be the annoying part
ye
channel_id = self.log_channels.get(str(ctx.guild.id))[0]
channel = self.client.get_channel(int(channel_id))
embed = discord.Embed(title=f"Muted | {user.name}",color=0xff0000)
embed.add_field(name="User",value=f"<@{user.id}>",inline=True)
embed.add_field(name="Moderator",value=f"<@{ctx.author.id}>",inline=True)
embed.add_field(name="Reason",value=reason,inline=True)
time = datetime.datetime.utcnow()
embed.set_footer(text = time)
await user.add_roles(muted)
await channel.send(embed=embed)
``` Why doesn't this send the embed in the channel? It doesn't error either
Anyone have bot ideas?
Any clue? xd
It mutes and unmutes perfectly just doesnt log where it should
Yeah that's all good dw
Just doesn't log
does the bot have permissions to send the embed?
It should
it does
print the channel before you send and check the id is right
Not ctx lol channel.send
print(channel) ?
i don't like working together so no
yeah, if it's None then you haven't fetched it, would usually throw an error though
It doesn't print anything

I mean the log thing worked perfectly fine with my kick command
That's what confused me
you cant print nothing
only with the end kwarg in the print function
Do you know whether the code gets that far?
It does since it gives the muted role and removes the role after the asyncio is done
And the embed is before that
lol i found a vps 4 vCore RAM 8GB SSD 160GB at 1β¬/month for 6 month
channel_id = self.log_channels.get(str(ctx.guild.id))[0]
All I know is that you're trying to print something and it doesn't appear, but the code after it succeeds. No that's not enough to come up with anything to try, sorry.
you're just grabbing the first channel id in a guild?
try putting a specific channel id in there and see if it sends
Sure, but it's just really weird that it doesn't log it. On the kick command it's basically the same code but there it logs
Just channel_id = 962982270204018708
I know..
yeah, it should be an int so that's right
Yeah alright
How can I load cogs because you can't await outside of async functions?
for filename in os.listdir("./cogs"):
if filename.endswith(".py"):
await bot.load_extension(f'cogs.{filename[:-3]}')
What where
π
Doesn't log either
You could put it inside setup_hook
You'd have to change your bot constructor though
try this await client.fetch_channel(channelId)
If you haven't already subclassing commands.Bot
I'm about to sleep
guys how to publish code to github from scratch
Use git
@dull terrace
yeah idk what your issue is, some weird thing is going on
i can literally show you it works
It worked fine with kick
Hmm
Ignoring exception in on_command_error
Traceback (most recent call last):
File "/home/runner/bbbb/venv/lib/python3.8/site-packages/discord/client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "main.py", line 113, in on_command_error
raise error
File "/home/runner/bbbb/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "/home/runner/bbbb/cogs/moderation.py", line 82, in kick
channel = self.client.get_channel(int(channel_id))
ValueError: invalid literal for int() with base 10: '[#962982270204018708](/guild/267624335836053506/channel/962982270204018708/)'
