#discord-bots

1 messages Β· Page 969 of 1

slate swan
#

delete the last coroutine and use listen

cloud dawn
#

de-indent process command

slate swan
#

!d discord.ext.commands.Bot.listen or just use listen on all events

unkempt canyonBOT
#

@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...
umbral night
slate swan
#

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

cloud dawn
slate swan
cloud dawn
#

πŸ˜”

slate swan
umbral night
#

what

#

am i not supposed to name it client

slate swan
#

no

umbral night
#

what

slate swan
#

you shouldnt its bad variable naming

umbral night
#

oh

#

i can change it?

slate swan
#

yes

cloud dawn
slate swan
#

what should i use to let the bot take the whole line in one arg rather than arg1 arg2 and so on

slate swan
slate swan
#

just want the bot to take the whole user input in a single arg

slate swan
#

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😳

cloud dawn
#

I'll see you back in 5 years, the art of regex requires meditation in a cave for the first 2 years,

slate swan
#

πŸ™

cloud dawn
#

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")

unkempt canyonBOT
#

@cloud dawn :white_check_mark: Your eval job has completed with return code 0.

re is a lib yes
slate swan
final iron
#

You missed a comma

slate swan
#

bro

final iron
#

Smh

cloud dawn
# slate swan he wants a filter so its not convenient

!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")

unkempt canyonBOT
#

@cloud dawn :white_check_mark: Your eval job has completed with return code 0.

ded
slate swan
#

bro

#

its a filter

cloud dawn
paper sluice
#

!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))
unkempt canyonBOT
#

@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
slate swan
umbral night
#

is there a way to write a description in an embed without doing description = (description)

paper sluice
cloud dawn
#

Re is more used for advanced string manipulation.

umbral night
#

like embed.set blablabla

slate swan
#

How do I send a video with my bot? like ctx.send(url=url)

cloud dawn
jagged adder
slate swan
jagged adder
#

It will embed itself

cloud dawn
slate swan
#

lmao I really was overthinking that

jagged adder
#

Lol

#

I do it sometimes too

slate swan
#

Thank you though bro

jagged adder
#

Np

cloud dawn
#

Just like okimii is right now, regular python with fuzzy matching is enough.

slate swan
#

bro what

umbral night
#
  embed.set_description(f"id: {member.id}")

why doesnt this work?

umbral night
#

oh

cloud dawn
umbral night
slate swan
slate swan
umbral night
final iron
#

It's an example

#

So no

cloud dawn
#

Well unless the kwarg is called kwarg

umbral night
#

kwargs are the things in the brackets after

async def ####
#

right

unkempt canyonBOT
#

*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

slate swan
#

arguments that are called by there name

#

KeyWord ARGuments

cloud dawn
#

You can name them anything but it's called kwarg so everyone knows what you are referring to.

umbral night
#

where do i define kwargs

#

like

slate swan
#

bro

umbral night
#

they're the things after asyncdef

#

right

slate swan
#

no

cloud dawn
slate swan
#

theyre arguments in the parameters.

umbral night
#

i am not understandabling

#

nor does the world eat pie

paper sluice
#

!tags positional-keyword

unkempt canyonBOT
#

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)

cloud dawn
unkempt canyonBOT
#

@cloud dawn :white_check_mark: Your eval job has completed with return code 0.

{'a': 1, 'b': 2}
green bluff
#

didnt i await get_multiplier

torn sail
green bluff
#

so like

#

i dont get it

#

oh like

#

await (get_multiplier())[0]

torn sail
#

Yes but the await in the bracket

green bluff
#

oh

torn sail
#

Easier to just use multiple lines

vale wing
# green bluff didnt i await get_multiplier

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 😩

slate swan
#

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

vale wing
#

!d os.path.exists

unkempt canyonBOT
#

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).
vale wing
#

And yeah don't use txt files for data storage

slate swan
#

why not?

green bluff
#

why is it not running the whole thing

vale wing
#

Because that's cringe bad storage way

green bluff
#

it doesnt print

#

calculation

slate swan
torn sail
vale wing
#

Read this @slate swan

green bluff
#

tho

torn sail
#

The second one

umbral night
#

what does /n do

green bluff
torn sail
green bluff
#

oh lemme try

torn sail
#

So change that how u changed the one before

umbral night
#

how do i move text down a line

torn sail
#

New line?

umbral night
#

yeah

torn sail
#

\n

green bluff
umbral night
#

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

torn sail
#

Put it where u wanna break the line

umbral night
#

in the string?

#

do i not split it into two strings

torn sail
#

Yeah

torn sail
umbral night
#

'ashdiasdasoidiwq89udewjufe' /n '82uwd9j32iewh9ye0jwdiofjdwif8ew'

green bluff
torn sail
#

Ohh yeah

torn sail
#

Just 1 string

#

β€œLine one\nline two”

umbral night
torn sail
#

Nice

torn sail
umbral night
#

ohh

#

thankyou

torn sail
#

Yw

green bluff
#

why is debug 4 not printing

umbral night
#
# 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

green bluff
torn sail
green bluff
#

oh yea

umbral night
#
@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?

hazy oxide
#

does anyone know how to create slash command group in nextcord?

hazy oxide
#

if the guild has no guild icon. you'll get an error

umbral night
#

ohh

umbral night
# hazy oxide if the guild has no guild icon. you'll get an error
@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

hazy oxide
#
@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)
hazy oxide
umbral night
#

idk

#

thought itd work

umbral night
hazy oxide
#

oke

umbral night
#

is there no way to get the bot to say the server name

#

without putting it in the code?

#

or something

#

@hazy oxide

slate swan
#

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?

hazy oxide
umbral night
supple thorn
hazy oxide
umbral night
#

:I

supple thorn
#

What do you mean

umbral night
#

nothing happens pretty much

supple thorn
supple thorn
#

And share your full code of your main file

umbral night
#

the entire code?

supple thorn
umbral night
#

all my commands?

supple thorn
#

Something else could be fucking up your command

supple thorn
umbral night
#

ok

unkempt canyonBOT
#

Hey @umbral night!

You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.

umbral night
#

oh

supple thorn
#

!paste

unkempt canyonBOT
#

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.

supple thorn
#

Paste it here

#

And save it and send the link

umbral night
slate swan
supple thorn
hazy oxide
#

Or maybe you want to check in every server by putting server name

umbral night
supple thorn
#

It looks like you use 2 spaces for each indent in everywhere else

#

For the guild icon code it's 4 spaces

umbral night
#

what

supple thorn
#

Which is the recommended amount of spaces

slate swan
umbral night
hazy oxide
#

Is that a file that contains blacklisted words?

umbral night
#

can u show me it @supple thorn

#

can u do it for me pls

supple thorn
#

Yours is 2

umbral night
#
@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)```
umbral night
supple thorn
slate swan
supple thorn
#

Your ide should indent it normally

#

Which is 2

umbral night
#

ohh

umbral night
#

idk why

supple thorn
umbral night
#

idk what that is

supple thorn
#

And invoke the command

supple thorn
umbral night
supple thorn
#

I suggest learning python first before tackling on an advance lib

umbral night
#

:I

supple thorn
#

You don't even know what a print statement is so start at the beginning

umbral night
#
@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

supple thorn
#

But it doesn't

umbral night
supple thorn
#

So something is preventing it to work

supple thorn
umbral night
#

ohh

#

sorry. idk what i'd call that

#

i didnt think

supple thorn
#

It's called a print statement

umbral night
#

ok thx

#

so what print(embed)

supple thorn
#

Now add it to the command

umbral night
#

await print(embed)

supple thorn
#

πŸ˜”

supple thorn
umbral night
#

what

supple thorn
#

Print anything

umbral night
#

oh

#

ok

supple thorn
#

We just need to see if the command even runs

slate swan
umbral night
#

other stuff works fine

supple thorn
umbral night
supple thorn
#

He doesn't have icon defined

slate swan
#

well for me it works

supple thorn
#

You do

supple thorn
umbral night
supple thorn
#

ctx.guild.icon works fine

supple thorn
umbral night
#

πŸ˜”

#

dont judge me

#

i cant host using anything else

supple thorn
#

Self host

umbral night
#

i cant self host

supple thorn
#

Even a phone can host one

#

Or a raspberry pi

umbral night
#

πŸ˜” i dont have money

supple thorn
#

You have a phone or a laptop

#

Use that

supple thorn
umbral night
supple thorn
#

Replit has a bug where you're writing ghost code but replit doesn't save it

supple thorn
umbral night
#

id have to interupt every time i want to use it

#

wont i

umbral night
slate swan
umbral night
#

and i use a chromebook, i cant even get vsc

supple thorn
#

Okimii help

supple thorn
slate swan
supple thorn
#

I use my chromebook to code

umbral night
#

what!

#

ok teach me how

supple thorn
supple thorn
umbral night
#

wdym

#

the chromebook?

supple thorn
#

Do you own the chromebook or is a school letting you use it

supple thorn
#

Okay

slate swan
#

hi

#

my bot has strange http error when I want to use any command containing embed, how to fix it?

slate swan
boreal ravine
#

sure

slate swan
supple thorn
#

Okay

slate swan
#

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?

formal basin
#

When I’m using my sound bot it says ffmpeg not found when I’ve clearly installed it

slate swan
#

I mean, are you sending the webhook from a command or what?

slate swan
#

uh well, you could just get the channel id straightaway

#

ctx.channel.id

supple thorn
#

Hello ducky

slate swan
#

show the command

slate swan
slate swan
#

!paste

unkempt canyonBOT
#

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.

supple thorn
#

Hello ashley

green bluff
#

any idea why this doesnt work

#

i have debugged it in the terminal

#

it wont run after the execution line of my database

supple thorn
unkempt canyonBOT
#

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.

green bluff
#

i was showing the terminal but i already got answer

supple thorn
#

Oh

#

You could of just copy and pasted the console output

green bluff
slate swan
#

Why does my bot spam to any message if i embeded something but if its not embeded it doesnt spam?

formal basin
#

How can I convert this playing in a vc but not using ffmpeg

slate swan
umbral night
#

is a venv necessary?

#

@supple thorn

#

@slate swan

supple thorn
umbral night
#

i dont see other people with them

supple thorn
umbral night
#

oh ok

#

ok back to it then

slate swan
umbral night
#

k ty

placid skiff
#

it is easier to export an entirely virtual env instead of recreate it on an external machine

formal basin
#

Yo is there away to store more than 1 channel in a json file

tawdry perch
#

wdym

placid skiff
#

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"}
]}
rocky hornet
#

whats the best way to organize lots of cogs?

placid skiff
#

wdym?

rocky hornet
#

directory structure

placid skiff
#

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

rocky hornet
#

then this folder becomes huge

placid skiff
#

depends

rocky hornet
#

i could have folders too

placid skiff
#

importing them will be a messy

rocky hornet
#

because folders can be loaded as modules if they have __init__.py

#

so i could create a folder for each category of commands

placid skiff
#

cogs folder should not have an init module, I use my cogs to categorize commands and events

placid skiff
#

then my other stuff like checks, tasks and others will be in another folder, separated by category

#

because is the best practice

rocky hornet
#

an example

placid skiff
#

yup this is good

rocky hornet
#

but its the same what i mean

quick garnet
#

Does anyone have an invite tracker source code for me?

placid skiff
#

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
placid skiff
placid skiff
#

you can ignore the commands the main things which does the trick are the events

slate swan
#

bro why are these slash commands not syncing, it's been like 5 houes

placid skiff
#

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

slate swan
placid skiff
#

then the problem is not yours xD

tiny ibex
#
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?

slate swan
#

there's no problem anywhere, don't know why it's not working

slate swan
#
await (bot.get_channel()).send()```
tiny ibex
slate swan
slate swan
tiny ibex
#

The issue is never with sending msgs

slate swan
#

well, then tell me what the issue is

tiny ibex
#

Eof

slate swan
#

and files should be a list

slate swan
tiny ibex
#

It can also be a BytesIO object afaik

junior verge
#
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?
slate swan
slate swan
#

!d discord.TextChannel.send

junior verge
#

ah

unkempt canyonBOT
#
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**.
tiny ibex
slate swan
#

lemme check

tiny ibex
#

Hm

junior verge
#
json.dump("logs.json", f)
``` like that?
tiny ibex
#

Why am I using files

#

When I need to use file

#

Well doesn't matter

#

Same issue

slate swan
#

nvm, readthedocs never gonna open on my phone ever again

junior verge
slate swan
tiny ibex
#

An audio

slate swan
slate swan
junior verge
tiny ibex
#

I don't see that weird

#

Many APIs return audio

#

Even spotify

#

Β―\_(ツ)_/Β―

slate swan
#

is there a package for forms?

slate swan
junior verge
#

pip install discord-ext-forms

slate swan
#

why-

tiny ibex
slate swan
slate swan
tiny ibex
#

Language totally doesn't matter

junior verge
#

Oh okay

#

No clue actually

tiny ibex
slate swan
#

!d discord.ui.Modal

unkempt canyonBOT
#

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...
junior verge
#

Ah it's new in 2.0

slate swan
maiden fable
junior verge
#
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?
maiden fable
#

Scopes

#

Use an instance variable

junior verge
#

How?

placid skiff
maiden fable
#

self.log_channels = json.load(f)

junior verge
#

And then ```py
channel_id = self.log_channels.get(str(ctx.guild.id), '0')

maiden fable
#

Yea

#

BTW is it a dict?

#

Then no need for the 0. It will automatically return None

junior verge
placid skiff
#

why casting a string on the guild id? D_D

placid skiff
#

get takes int

junior verge
#

Ah yeah

maiden fable
#

In a JSON

placid skiff
#

oh hahahahaha

#

my bad

junior verge
#

Wait so leave the str or?

#
channel_id = log_channels.get(str(ctx.guild.id)
``` Just like that then
maiden fable
#

Yea leave it. But don't forget to turn it to int while using get_channel

junior verge
#

Aight let me see

#
channel = self.client.get_channel(channel_id)
``` It says that it's invalid syntax
maiden fable
#

Heh

#

Prolly a missing closing bracket

junior verge
#

Yeah haha

#

Sorry

#

Now it says that self isn't defined hm?

vale wing
#

Is it in cog

junior verge
#

Yes

vale wing
#

If so first arg of the function must he self

junior verge
#

I know

maiden fable
junior verge
#

I got that

#
async def kick(self, ctx, member: discord.Member, *, reason=None):
vale wing
#

Then it can't be undefined

#

Unless it is in some other function

junior verge
#

What do you mean by that

slate swan
vale wing
#
async def kick(...):
    await some_func()

async def some_func(...):
    # do stuff```
maiden fable
junior verge
vale wing
#

Ok could you show full kick command

junior verge
#

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}**')
vale wing
#

Weird

maiden fable
#

ctx.bot

#

And if it isn't a cog, remove self

junior verge
#

It's cog.

slate swan
#

my bad

maiden fable
#

It's still against ToS to stream music via the raw API

slate swan
#

even non-copyright sounds

#

?

junior verge
maiden fable
#

Mhm, still against ToS

junior verge
#

You need to own the music

vale wing
#

Depends what service you use

maiden fable
junior verge
#

I use client though?

vale wing
#

Pretty sure soundcloud allows streaming audio

maiden fable
junior verge
#

And where on what line

maiden fable
#

Instead of self.client, use ctx.bot

junior verge
#

Let me see

vale wing
#

That thing is rarely used

junior verge
#

Same error

vale wing
#

Self not defined?

junior verge
#

Nameerror self is not defined

vale wing
#

Could you give full traceback

junior verge
#

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
maiden fable
#

Paste whole code

#

And do the open() in the init

vale wing
#

It's in different function lmao

junior verge
#

Huh

vale wing
#

Self is not defined in static load or smth

junior verge
#

Whats that

vale wing
#

You need to define it in _init_

junior verge
#

How?

#

My init file is empty

vale wing
#

I mean init function

junior verge
#

oh

vale wing
#
class MyClass:
    def __init__(self, bot):
        self.bot = bot```
junior verge
#
class Moderation(commands.Cog):
    def __init__(self, client):
        self.client = client
#

I got that

vale wing
#

Yes

#

And load json in there as well

junior verge
#

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?
vale wing
#

Yes but indent the with content

junior verge
#

the last 2 lines?

vale wing
#

One

junior verge
#

the with open as the same indent as def?

vale wing
#
with create_thing() as something:
    do_stuff_with(something)```
junior verge
#
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?
vale wing
#

Yes

junior verge
#

And in my code?

#

Leave the client.bot?

vale wing
#

No wtf

junior verge
#

Or can I use self.client

vale wing
#

self.client

junior verge
vale wing
#

We fixed your issue

#

And it was in a different place

junior verge
#

Let me see if it works

vale wing
#

Both self.client and ctx.bot will work but self.client is more suitable

junior verge
#

log_channels is not defined

vale wing
#

self.log_channels

junior verge
#

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

slate swan
#

your channel_id variable is somehow a list

junior verge
#

Erm yeah, got any idea on how I could fix that?

placid skiff
#

!e

unkempt canyonBOT
#
Missing required argument

code

placid skiff
#

!e

dct = {"abc": 1, "cdb": [1, 2]}

print(f"{dct['abc']} {dct['cdb']}")
unkempt canyonBOT
#

@placid skiff :white_check_mark: Your eval job has completed with return code 0.

1 [1, 2]
placid skiff
#

probably he has something like this

outer parcel
#

Is there a way to stop discord.ui.button from timing out

stiff nexus
#

help ```py
ImportError: cannot import name 'format_dt' from 'discord.utils'

slate swan
green bluff
#

!json

unkempt canyonBOT
#

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.

green bluff
#

!db

#

!d

unkempt canyonBOT
rocky hornet
#

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

sullen pewter
#

How to fix this error?

rocky hornet
#
cogs/
    general/
        ping.py
    google/
        __init__.py # loads what needed itself
        translate/
            api.py
            __init__.py
rocky hornet
sullen pewter
#

How to remove it

rocky hornet
#

delete the last few symbols and retype manually

#

ah

pliant gulch
#

In python, the \ character is an escape character

rocky hornet
#

u didnt escape backslashes

pliant gulch
#

You need to escape the escape character

rocky hornet
#

or use literal string r"my\path"

rocky hornet
green bluff
blissful sparrow
#

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)
hazy oxide
#

does anyone know how to create slash command group in nextcord?

serene lynx
#

how to get list banned on guild with nextcord?

unkempt canyonBOT
#

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.
hazy oxide
flat solstice
#

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.

#databases message

odd walrus
#

is there a way to make a hard space/nbsp in discord embed

flat solstice
serene lynx
#
  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
hazy oxide
#

Create a variable first

serene lynx
#

done

#

bannnedUsers = await interaction.guild.bans()

inner wing
#
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
muted dagger
#

i need a avatar command for hikari-lightbulb which shows a targets avatar

shrewd kraken
#

is it possible to use commands.Cog.listener() to detect commands

shrewd kraken
junior verge
#

What variable?

supple thorn
#

Also why would you

slate swan
junior verge
#
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'
shrewd kraken
supple thorn
junior verge
shrewd kraken
supple thorn
supple thorn
#

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

slate swan
#

!d discord.ext.commands.Context.command will return a command if its a command, else None or maybe a attr error

unkempt canyonBOT
slate swan
slate swan
#

lemme check the src

shrewd kraken
#

(although i think i should just put the logger in the command)

slate swan
shrewd kraken
#

you're passing channel_id into self._private_channels

junior verge
#

Me?

shrewd kraken
shrewd kraken
junior verge
#

So what do I do to fix that?

shrewd kraken
#

oh and channel_id is a list

junior verge
#

Yeah I think that's the issue

junior verge
flat solstice
unkempt canyonBOT
#
Nah.

No documentation found for the requested symbol.

shrewd kraken
#

wait that's a thing?

slate swan
#

yep

flat solstice
junior verge
#

@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}')
slate swan
#

you can use the 1st one or the 2nd one

slate swan
#

the 2nd one gets called only when the command works without any error

shrewd kraken
#

the error is in the kick cmd

junior verge
#

Okay

shrewd kraken
#

can you show the code of the kick cmd?

shrewd kraken
junior verge
#
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}**')
shrewd kraken
junior verge
#

Sure

shrewd kraken
#

it needs the bot inside the server

junior verge
shrewd kraken
#

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

placid skiff
junior verge
#

I had that but they told me to remove it

shrewd kraken
junior verge
junior verge
#

I mean it put a <#> in the json

placid skiff
junior verge
#

Yeah I see, where do I fix that?

slate swan
placid skiff
junior verge
#
log_channels[str(ctx.guild.id)] = channel.split()
``` Is it because of the str?
shrewd kraken
placid skiff
#

if you wait for an event in the function of the command that it will not be finished until that event is resolved

slate swan
junior verge
slate swan
#

the complete callback comes under its functioning

junior verge
#

And that's in the kick command then?

junior verge
#

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}')
placid skiff
supple thorn
#

Hello blvck

placid skiff
#

!e

str1 = "123_abc"
str2 = "456_dbe"

print(str1.split('_'))
print(str2.strip('_'))
unkempt canyonBOT
#

@placid skiff :white_check_mark: Your eval job has completed with return code 0.

001 | ['123', 'abc']
002 | 456_dbe
junior verge
#
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
pliant gulch
junior verge
#

Anyone any idea on how to fix it

slate swan
#

if that's the case, ctx.response.send_message("your message here") should work

#

i could be terribly wrong tho

slate swan
#

is it possible for the bot to change a channel name

#

the channel is already created

slate swan
#

!d discord.TextChannel.edit

unkempt canyonBOT
#

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...
slate swan
# slate swan Yes

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

boreal ravine
#

don't do it in on_ready

slate swan
slate swan
boreal ravine
slate swan
#

Nvm πŸ’€

#

WAIT

#

!d discord.ext.tasks.loop

unkempt canyonBOT
#

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").
slate swan
#

Finally-

slate swan
hollow badger
#

Please don't use ableist language. Thanks πŸ™‚

slate swan
#

!d discord.Embed.set_thumbnail

unkempt canyonBOT
#

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.
crimson compass
slate swan
#

yes thats the thumbnail

blissful sparrow
#

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?

odd walrus
slate swan
slate swan
blissful sparrow
#

not possbile to do 2 to 2?

#

gonna make said embed look ugly otherwise

slate swan
#

not sure

hasty bison
#
    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)
blissful sparrow
#

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=?:
slate swan
#

and it works

flat solstice
slate swan
#

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

slate swan
#

when you could just do str(len(client.guilds)), or even just len(client.guilds) would work.

slate swan
#

but it still works

slate swan
#

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?

slate swan
#
# otherfile.py

my_variable = "here"```
```py
#mainfile.py
from otherfile import my_variable``` basic python imports
boreal ravine
#

Anyone have a good bot idea

unkempt canyonBOT
#

Hey @slate swan!

You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.

slate swan
boreal ravine
slate swan
#

the classic bingo game?

boreal ravine
#

and how would that work

slate swan
#

google it

boreal ravine
boreal ravine
slate swan
boreal ravine
slate swan
boreal ravine
#

for that I'd need an API

#

idk which API does that, and I'm too lazy to find one

paper sluice
#

i saw a movie api called TMDB the other day

#

.

crimson compass
#
        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)```
paper sluice
#

embed=embed :)

crimson compass
#

aa

paper sluice
#

u need to pass it as a kwareg

slate swan
#

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

boreal ravine
#

@paper sluice thanks

hushed galleon
crimson compass
slate swan
#

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

magic stump
#

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)

magic stump
#

if "!" in nick.content:
AttributeError: 'str' object has no attribute 'content'

quaint epoch
#

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

paper sluice
magic stump
#
@bot.command()
async def reg(ctx, nick):```
crimson compass
quaint epoch
#

hey, can you typehint values as a timedelta?

paper sluice
quaint epoch
#

lemme find out

magic stump
quaint epoch
#

oh wow

#

wowowowow

dull terrace
#

anyone know where to get some creative commons pixel art playing cards

#

i caaaant bring myself to draw 52 cards

quaint epoch
#

you wanna play poker over discord?

dull terrace
paper sluice
#

what is the output?

crimson compass
hushed galleon
# slate swan using nextcord

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

slate swan
crimson compass
#

a

paper sluice
quaint epoch
#

guess my job here is done

paper sluice
#

so whats wrong?

quaint epoch
#

embed.set_image(discord.File)

quaint epoch
#

so for example embed.set_image(discord.File(r'fp'))

dull terrace
#

am i gonna have to code something just to draw these cards for me

quaint epoch
quaint epoch
dull terrace
slate swan
#

i think this fixes my problem

quaint epoch
slate swan
#

repeat*

quaint epoch
slate swan
#

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

dull terrace
quaint epoch
#

im asking for context to question to help you

dull terrace
#

although i have no idea if this is gonna be any faster sadcat

slate swan
quaint epoch
#

(lancer theme intensifies)

slate swan
#

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

quaint epoch
#

if you can read the file, yes

slate swan
#

k
h o w

sick birch
#

In your on message, if the message is from a certain guild, then do a blank return

quaint epoch
#

!e import json
json.dumps(["hello", "world"])

unkempt canyonBOT
#

@quaint epoch :warning: Your eval job has completed with return code 0.

[No output]
quaint epoch
#

okay yeah, just store the list in a file/db, read and you're good to go

slate swan
#

wait if there anything like
if guild.id is 1234567: return?

#

or something like that

quaint epoch
slate swan
#

ok

quaint epoch
#

guild id: 696969696969 is blacklisted

slate swan
#

sus but ok

quaint epoch
#

so, we put that id in a list in a json file

#

json file looks like - ["696969696969"]

#

now we do blacklist = json.loads(file)

slate swan
#

no wait

#

just tell me if there is single line code to do this

#

just like i said in the code block

quaint epoch
#

your loss

slate swan
#

kden'

quaint epoch
#

gimme a sec

slate swan
#

sec

quaint epoch
#

πŸ‘€

#
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"]

junior verge
#
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}**')
paper sluice
#

i think u need to have members and guilds intents on to use get_channel

junior verge
quaint epoch
#

channel, isn't a channel object

quaint epoch
#

it's a no return

paper sluice
#

oh uea

junior verge
#

So how do I fix that, don't fully get it.

paper sluice
#

discord.Object(id=...)

junior verge
#

Hm?

quaint epoch
#

print(channel_id, type(channel_id))) and tell me how that goes

junior verge
#

Sure

quaint epoch
#

the id might not have been valid

junior verge
#

Does it matter where?

quaint epoch
junior verge
#
{"873510385871904838": ["962982270204018708"]}
``` Does this maybe need to have <#> ?
quaint epoch
junior verge
#

alr

quaint epoch
#

don't snow me the json file

junior verge
#

Relax

quaint epoch
#

heheheheh, snow

slate swan
junior verge
#

I don't know why it did that

slate swan
#

Are they supposed to be multiple?

quaint epoch
junior verge
quaint epoch
#

discord expected an int, and you got a string in a list

junior verge
#
channel_id = self.log_channels.get(str(ctx.guild.id))[0]
``` so change the str to a int there?
junior verge
#

oh

quaint epoch
#

channel = self.client.get_channel(int(channel_id))

#

you probably did py import tracemalloc tracemalloc.start()?

junior verge
#

uh no

quaint epoch
quaint epoch
junior verge
#

Oh wow it just works now

#

What did you change?

quaint epoch
#

when you fetched the channel, it expected an int for the id, you passed a string

#

so it was a convert

dull terrace
#

froggy_chill 50% of the way to making the code draw it for me

#

why does the Q look like a O suspicious god dammit

#

slowly gettin there, just gotta add some sort of image which is gonna be the annoying part

#

ye

junior verge
#
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
boreal ravine
#

Anyone have bot ideas?

junior verge
#

It mutes and unmutes perfectly just doesnt log where it should

#

Yeah that's all good dw

#

Just doesn't log

boreal ravine
dull terrace
#

is it fetching the channel properly

#

correct channel?

junior verge
junior verge
dull terrace
#

print the channel before you send and check the id is right

junior verge
#

Not ctx lol channel.send

junior verge
boreal ravine
#

i don't like working together so no

dull terrace
dull terrace
junior verge
#

That's what confused me

slate swan
#

only with the end kwarg in the print function

junior verge
#

But how do I fix this issue?

#

print(channel) just does nothing in the console

minor totem
#

Do you know whether the code gets that far?

junior verge
#

It does since it gives the muted role and removes the role after the asyncio is done

#

And the embed is before that

placid skiff
#

lol i found a vps 4 vCore RAM 8GB SSD 160GB at 1€/month for 6 month

junior verge
#

nice

#

@minor totem Got any idea?

dull terrace
minor totem
#

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.

dull terrace
#

you're just grabbing the first channel id in a guild?

#

try putting a specific channel id in there and see if it sends

junior verge
#

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

junior verge
junior verge
#

I know..

dull terrace
#

yeah, it should be an int so that's right

junior verge
#

Yeah alright

slate swan
#

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]}')
junior verge
supple thorn
#

You'd have to change your bot constructor though

dull terrace
supple thorn
#

If you haven't already subclassing commands.Bot

junior verge
#

Kick doesn't log now either

#

Here look

supple thorn
#

I'm about to sleep

junior verge
#

!paste

cosmic agate
#

guys how to publish code to github from scratch

junior verge
#

Use git

cosmic agate
#

how

#

i have installed it

junior verge
junior verge
dull terrace
#

yeah idk what your issue is, some weird thing is going on

#

i can literally show you it works

junior verge
#

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/)'
dull terrace
junior verge
#

Yeah I know.

#

Saw my error?

dull terrace
#

oh okay

#

you need to split the string before turning it into int

#

or slice