#discord-bots

1 messages · Page 729 of 1

slate swan
#

I have save the token into secrets option

untold token
#

Yeah no problem

light violet
#

and u r done

#

for replit

honest shoal
light violet
untold token
#

Yeah that will work too

#

It returns a string

#

so for example

light violet
#

what do u need

honest shoal
#

hmm

untold token
#
import os
data = os.getenv("token")  #  gets the value associated with the key token

bot.run(str(data))  # just to be sure, we explicitly cast it into a string
light violet
#

just add bot.run(data)

#

it would work

untold token
#

Just to be sure

#

explicitly casting to make it is always string

light violet
#

hm i tested it i am a proffesional py bt dev and currently working on antinuke bot of mine fastest antinuke

#

;aw;

untold token
#

Okay.....

light violet
#
@client.event
async def on_guild_member_update(oldMember,newMember):
    try:
        guild = oldMember.guild
        logs = await guild.audit_logs(limit=1, action=discord.AuditLogAction.member_role_update).flatten()
        logs = logs[0]
        reason = "Upadted Member As Non-Whitelisted User"
       
        
        
        await logs.user.ban(reason=f"R-Dynamic Protection System | {reason}")
      
    except:  
        pass 

is this correct?

#

for banning members on adding roles

slate swan
#

Dine it works.
Thank you so much to all

light violet
light violet
untold token
#

This is a bad practice

#

Your errors get eaten up and you don't know what's happening

#

Use traceback to print whatever errors that occurs when someone happens

#

!d traceback.print_exc

unkempt canyonBOT
#

traceback.print_exc(limit=None, file=None, chain=True)```
This is a shorthand for `print_exception(*sys.exc_info(), limit, file, chain)`.
honest shoal
untold token
#

In some cases where you know the error doesn't matter, you can bare try excepts but most of time, you should always try except for specific Exceptions

honest vessel
#

is there a way with disnake slashcommand to add more description for optional?

#

even tho it self-described but would like to specific it with "The message you would like others to see when tag you."

light violet
fringe harness
#

u can but u have to have them as secrets

untold token
#

You can use a docstring to add description to your argument and disnake will parse it from your docstring

#

For example

honest vessel
#

yes example 🙂

#

this is what i have now ```py
@commands.slash_command(description="Show others that you are Away From Keyboard.")
async def afk(self, inter, *, message="no reason given."):

#

while we also on it is it possible to have aliases for slashcommands?

light violet
#

@untold token bro tell

lapis breach
#

i watched it but idk why but i was getting an error so i setup my repo using github desktop

light violet
#

@lapis breach what do u need

untold token
#
@bot.slash_command(name="test", description="stuff")
async def func(inter: disnake.ApplicationCommandInteraction, input: str = "stuff"):
    """
     ...
     
    Parameters
    --------------
    inter : disnake.ApplicationCommandInteraction
      Stuff here 
   
   input : str
       your description for input here
   """
    
    #  rest of your code
#

@honest vessel this is one way to add descriptions

lapis breach
untold token
#

Another way is

light violet
#

@lapis breach oo

untold token
#
from disnake.ext.commands import Param



@bot.slash_command(name="test", description="stuff")
async def func(inter: disnake.ApplicationCommandInteraction, input: str = Param(description="your description here", default="stuff"):
    #  rest of your code here
honest vessel
#

i like the second more

#

thanks brother

lapis breach
light violet
#

@lapis breach hm

untold token
untold token
lapis breach
untold token
light violet
#

@lapis breach i dk how to create py buttons

untold token
#

You can use third party libraries to create buttons for dpy version below 2.0

light violet
#

@untold token how to remove all role bro from a certain user

untold token
#

But as i said, it's not recommended

lapis breach
untold token
#

!d discord.Member.roles

unkempt canyonBOT
#

property roles: List[Role]```
A [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.9)") of [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role") that the member belongs to. Note that the first element of this list is always the default [‘@everyone](mailto:'%40everyone)’ role.

These roles are sorted by their position in the role hierarchy.
untold token
#

!d discord.Member.remove_roles

unkempt canyonBOT
#

await remove_roles(*roles, reason=None, atomic=True)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Removes [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role")s from this member.

You must have the [`manage_roles`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.manage_roles "discord.Permissions.manage_roles") permission to use this, and the removed [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role")s must appear lower in the list of roles than the highest role of the member.
untold token
light violet
#

@untold token bro remove role from a particular user like await newMember. remove_roles

#

now?

untold token
#

I did not understand what where you trying to say

untold token
untold token
honest vessel
#

@untold token thank you that was badass perfect!

tidal hawk
#

Can a bot create_invite on somebody other's name?

honest vessel
#

no lol

lapis breach
untold token
#

You should read the disnake docs

lapis breach
honest vessel
#

@tidal hawk but it can give an already created invite from another user

light violet
#

@untold token i need the code to remove roles from newmember

#

all roles

tidal hawk
#

What's the best method for determing who invited a user into a guild?

untold token
#

You just need to loop through

#

I am not going to spoonfeed you

#

Also aren't you professional python bot developer?, you should know this by then

tidal hawk
honest shoal
untold token
#

Then you can do it

light violet
#

btw proff at js actually py intermediate

untold token
light violet
#

🙄

#

i shifted to py for faster reponse

untold token
#

Bruh?

solar anchor
#

can someone help me with a bot that says "pong" if i type /ping

#

ive een trying for 2 days and i just get errors

untold token
#

You need to create a command with the prefix /

solar anchor
#

i cant connect my bot to my ode

untold token
#

If it is a text command using the commands framework then

light violet
#

@solar anchor
@client.command()
asyns def ping(ctx):
await message. channel. send("Pong" )

#

may be this u nees

honest shoal
#

!code

honest vessel
#

would't commands with prefix / be annoying af always get the built-in slashcommans showing up

light violet
#

ohl

solar anchor
#

well then another prefix idgaf

untold token
#
@bot.command(name="ping")
async def ping_command(ctx: commands.Context):
   await ctx.send("pong")  #  sends the message where the command was invoked
solar anchor
#

but i cant connect my bot to my code

untold token
#

Did you call the run() method?

honest vessel
#

i have a fetish of having . as prefix

light violet
#

client = discord. client( command_prefix='/',)

untold token
#

!d discord.ext.commands.Bot.run

unkempt canyonBOT
#

run(*args, **kwargs)```
A blocking call that abstracts away the event loop initialisation from you.

If you want more control over the event loop then this function should not be used. Use [`start()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot.start "discord.ext.commands.Bot.start") coroutine or [`connect()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot.connect "discord.ext.commands.Bot.connect") + [`login()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot.login "discord.ext.commands.Bot.login").

Roughly Equivalent to...
light violet
#

.

untold token
#

That's wrong

solar anchor
#

how do i connect my bot to my code???

light violet
#

hmm

solar anchor
#

if i do import discord it gives errrors

honest shoal
honest vessel
#

then you havnt installed library correctly

untold token
#

discord.Client() has no keyword argument as command_prefix

solar anchor
untold token
#

You need to use commands.Bot aka, commands framework

honest vessel
#

use pip

solar anchor
#

i tried

#

didnt work

untold token
#

This is a good example

honest vessel
#

@solar anchorwhat error did u get?

solar anchor
light violet
#

@solar anchor u need this

intents=discord.Intents.all()
intents.members = True

client = commands.Bot(command_prefix=commands.when_mentioned_or("/"), case_insensitive=True, intents=intents)
velvet compass
#

That is in the python REPL

honest vessel
#

that is python interpeter

untold token
#

^

solar anchor
#

what do i do

velvet compass
#

Ctrl+z and enter

solar anchor
#

and then?

velvet compass
#

py -m pip install discord

light violet
#

@untold token yep sory

velvet compass
#

Also, how familiar are you with Python?

light violet
#

sorry abouy that

solar anchor
honest shoal
#

no pip

honest vessel
#

your still in the python interpeter...

velvet compass
#

See those >>>?

solar anchor
honest vessel
#

close it

solar anchor
untold token
#

You are trying to run the code through a python REPL

velvet compass
#

That means you are in the python interpreter / REPL

untold token
#

discord.Intents.all() already enables all the intents needed

spring flax
#

why doesn't await channel.edit(slowmodde_delay=seconds) change the slowmdoe? No errors, no eh's

light violet
solar anchor
honest vessel
#

@solar anchor close it open new cmd 🙂 and type the command he gave u

light violet
#

seconds

honest vessel
#

close the CMD / Prompt

#

python interpeter

light violet
#

import discord would work

solar anchor
#

it doesnt

untold token
#

If you are on vscode, you can press CTRL + `

spring flax
untold token
#

That opens a new terminal

solar anchor
#

okay done

spring flax
#

I was expecting an error atleast

solar anchor
#

now what?

velvet compass
light violet
#

@spring flax what is ur cmd

honest vessel
#

now type the command he gave u

solar anchor
#

yayy

honest vessel
#

xD

solar anchor
#

its installing!

light violet
#

@solar anchor hmm nice

honest shoal
#

nice

light violet
#

@velvet compass wont import discord work?

honest vessel
#

now turn on matrix themesong clubbed to death 😄

velvet compass
light violet
#

hm btw they r same lmao

velvet compass
#

Its not a built in

untold token
#

It needs to be installed

light violet
untold token
#

First

light violet
#

and it works

velvet compass
#

Sure

honest vessel
#

right

untold token
light violet
#

@untold token ya

honest vessel
#

i would love to see python put discord.py as core library 😄

solar anchor
#

where was that example?

light violet
#

do anyone know the lang nextcord?

untold token
#

Because replit has UPM (universal package manger) which reads your imports and guesses your libraries and installs it for you

light violet
#

@untold token hmm

untold token
light violet
#

yep

solar anchor
#

nvrm found it

light violet
#

btw its is better than dc py

honest vessel
#

its same lang tho

solar anchor
#

um guys

light violet
#

yep btw i heard it is better never tried though

#

how of u guyz made a antinuke bot?

honest vessel
solar anchor
untold token
#

Yeah disnake is much better

velvet compass
solar anchor
#

but

untold token
#

Yeah your library has installed

honest vessel
#

@solar anchorrun that pip update it askes for 😉

untold token
#

The warning is just that your pip is not updated to the latest version

velvet compass
#

pip updates all the time, so that is a pretty common message to update to the latest and greatest

honest vessel
solar anchor
#

o

velvet compass
#

py -m pip install --upgrade pip for windows (using the py launcher is very handy)

honest vessel
#

^

solar anchor
#

oopsie

#

thanks guys!!

honest vessel
#

happy hakking

solar anchor
#

haha

velvet compass
#

So are we still "fkn useless"?

honest shoal
#

sadge

solar anchor
#

was frustrated

untold token
#

Who said that

solar anchor
#

i did in general cuz ive been struggling with this for 2 days

#

i apologize guys

#

its still yellow

#

idk

honest shoal
solar anchor
#

i did not

honest shoal
#

do it

honest vessel
#

he said do it!

honest shoal
#

lawl

solar anchor
#

i did it!

honest vessel
#

take a kneel

solar anchor
#

it works (:

honest vessel
#

@solar anchorall wanna be ur friend now when u making awesome bots your friends gonna be like 🤤

solar anchor
#

lmaoo

honest vessel
#

(motivation speech)

solar anchor
#

xDD

#

for sure!

honest vessel
#

and be ready to buy a wig, cause you gonna ripp of some hair in frustration when get errors / stuck

#

but this place always helpful

honest shoal
solar anchor
#

lmao i know, ive been coding with C#

honest vessel
#

ah, then this should be way easier

solar anchor
#

python turrtle too

#

well i just need to figure it out

honest vessel
#

no brackets only tabs 😄

solar anchor
#

i made like 5 games with C#

#

lmao yes haha

honest vessel
#

cool

#

didnt make a new boom like minecraft?

#

simple concept huge potential crazy game

solar anchor
#

lmao i wish i was good enough to make a game like that

#

ill send u a vid of me speedrunning my game

honest vessel
#

ok

#

why not, am having a lil break anyway

untold token
#

!ot

unkempt canyonBOT
solar anchor
#

its not long

honest vessel
#

come here

ruby tinsel
#

can someone help me?

RuntimeWarning: coroutine 'Command.__call__' was never awaited
  with open('balance.json', 'r') as f:
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
Ignoring exception in on_message
Traceback (most recent call last):
  File "C:\Python39\lib\site-packages\discord\client.py", line 343, in _run_event
    await coro(*args, **kwargs)
  File "c:\Users\mdsuy\OneDrive\Documenten\DarkEmpireBot\currency.py", line 127, in on_message
    with open('balance.json', 'r') as f:
AttributeError: __enter__

My code always worked but when I tried to reboot my bot today this error came

ruby tinsel
# untold token Code?

@client.event
async def on_message(message):
    if message.author.bot == False:
        with open('balance.json', 'r') as f:
            users = json.load(f)

        await update_data_bal(users, message.author)
        await add_experience_bal(users, message.author, 1)
        await level_up_bal(users, message.author, message)

        with open('balance.json', 'w') as f:
            json.dump(users, f, indent=4)

    await client.process_commands(message)

this always worked till now

#

it works like this, if someone says something in the chat it adds + 5$ to their discord balance

untold token
#

Hmm

ruby tinsel
#

other commands arn't working either

#

same error

untold token
#

Although I would say this is not a good way for leveling up

ruby tinsel
#

its not a leveling command

untold token
#

If someone spams messages, its still going to count

ruby tinsel
untold token
#

I don't see any problem in this code though

#

Although I will suggest improvements

#

First of all

#

use an event listener

#

!d discord.ext.commands.Bot.listen

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

Example...
untold token
#

So for example

potent spear
honest vessel
#

@ruby tinselRuntimeWarning: Enable tracemalloc to get the object allocation traceback this usally (when using async) means u didnt await it

ruby tinsel
potent spear
honest vessel
#

i use json for AFK system, and database for streamers+check if live n update etc

potent spear
honest vessel
#

json is a textfile thats all 😄

potent spear
#

json is for config

ruby tinsel
#

its working for me 💀

untold token
#
@client.listen()
async def on_message(message: discord.Message):
    if message.author.bot:
      return
    
   with open('balance.json', 'r') as f:
            users = json.load(f)

        await update_data_bal(users, message.author)
        await add_experience_bal(users, message.author, 1)
        await level_up_bal(users, message.author, message)

        with open('balance.json', 'w') as f:
            json.dump(users, f, indent=4)

    # await client.process_commands(message)
   #  no need to call this method as, it's an event listener and it's not overriding the default message event
potent spear
#

until it doesn't anymore, then you'll lose everything...

untold token
#

and yes

#

Do not use json as a database

#

Its not meant for it

#

If you really want a database similar to json syntax, use MongoDB

potent spear
#

this is clearly just a YT video...

honest vessel
#

i use json for simple afk system with msgs, but would't store data that is very important like xp, balance, etc

untold token
potent spear
#

the code you shared from him

untold token
#

Wdym

#

I just wrote it

potent spear
#

look at the function names... that's textbook YT

untold token
#

Oh that

honest vessel
untold token
#

Probably yes

ruby tinsel
#

I made the function names myself

honest vessel
#

kek

potent spear
untold token
#

Also, you should use event listeners rather than event as they are external and asynchronous

#

You can have multiple listeners of same event type and they will not interfere each other

potent spear
ruby tinsel
untold token
#

I mean, it does look like its copied

potent spear
untold token
#

Which is a very bad practice

honest vessel
#

put in aiosqlite in it !

potent spear
#

^^

honest vessel
#

and u set

untold token
#

Json is a format used to transfer data and communicate between different programming languages, servers, APIs, etc

#

It's not meant to be used as database

honest vessel
#

download DB Browser (sqlite) and create ur tables with GUI if u dont wanna write sql to create database n tables

potent spear
#

right, then use an async wrapper for that db and you're all set

honest vessel
#

aiosqlite

ruby tinsel
#

alright

honest vessel
#

then learn sql 😄

#

But u will love it!

slate swan
honest vessel
#

(its ok use json n learning, they prob find flaws later on anyway)

slate swan
#

Nosql databases are ez

honest vessel
#

why would't u wanna learn SQL? 😄

ruby tinsel
#

I already installed SQLite 2 weeks ago

slate swan
honest vessel
#

sqlite is handy if on same host

oblique cobalt
#

unless you know what ur doing

oblique cobalt
#

i literally just said "relationship"

#

lo

slate swan
#

💀ye but i want some examples doe

oblique cobalt
#

to fit that right, thats just what i heard from sql smarty pants

#

but eh, i wouldn't recommend ppl to use mongoDB for other reason, mainly because mongoDB developers not documenting things rights, so you have to use shitty drivers for it to work

slate swan
oblique cobalt
oblique cobalt
#

yep

slate swan
#

pithink imagine having 8mb only

#

in the db

oblique cobalt
#

rip

tacit token
#

hi guys, this shit never work.

oblique cobalt
#

it means user is none

#

either remove =None or add if statement to point it to author when nothing is being passed

#

@tacit token

tacit token
#

not work

oblique cobalt
#

not work what

potent spear
slate swan
#

Remove *, and mention a user

oblique cobalt
#

oh i didn't notice that

potent spear
#

he's also confusing himself by calling a member object a user

slate swan
#

And how can you be a Discord server developer

potent spear
#

he's developing bugs, let him be

cosmic socket
#

heloo,
im not the best programmer but I made an json to embed obj parser in python and thought it may be cool to share haha :3

For me its pretty useful, since I like to design embeds on https://discohook.org but they only show the embed as a json obj (at the bottom)
Its my first package ever, so please don't hate :3, you can find the package here: https://pypi.org/project/dj2e/

You can install it via pip install dj2e
(discord json 2 embed)

And use like the following example:

from discord.ext import commands
import js2em

bot = commands.Bot(command_prefix="!")

@bot.command()
async def test(ctx):
    embeds = js2em.jsonToEmbed('test.json')
    # jsonToEmbed takes a file-path and returns a list of all embeds in that json
    await ctx.send(embed=embeds[0])
bot.run(token)
slate swan
#

Hello everyone again can someone help me how can I find API, I mean from which site, for improving the bot feature. I have tried to find it, but not able.

kindred epoch
#

anyone have command ideas?

near sedge
#

do you have an event in that cog?

#

try removing commands.Context

#

if that doesn't work double check if your cog actually got authenticated to the bot its self

def setup(client):
    client.add_cog(nameOfYourCog(client))
#

if that also doesn't work then im not sure what could be causing this

slate swan
#

show the cog

#

ok so a command isnt found right?

#

or whats the error

#

by?

#

the command isnt found?

#

show me the full cog

#

in ban you forgot the self argument

#

to access the class

#

and your indentations arent correct

#

they should be indented with the init

#

delete 1 level of indentation

near sedge
#

oh yeah they are

slate swan
#

lol

#

nice

#

well now you know

#

LMAO

#

welp gtg see ya

#

no problem

near sedge
#

i have a question about mongoDB it gives me this traceback idk why it takes my on_ready command as a database object

Traceback (most recent call last):
  File "d:\Scripts For Python\Discord Bot-20211230T010404Z-001\Discord Bot\discordBotCore.py", line 37, in <module>
    async def on_ready():
TypeError: 'Database' object is not callable

im clueless 💀

#

thats the issue there is no object it should be calling

#

the database goes online normally, but then it doesn't launch the bot due to that

#

and then ends the script there

#

yea my on_ready command

#

event*

#

sure thing

#
client = pymongo.MongoClient(connection, serverSelectionTimeoutMS=5000)

try:
    print(client.server_info())
    print("Connection Established!")
    
except Exception:
    print("Seems like something went wrong connecting to the database.")

@client.event
async def on_ready():
    change_status.start()
    print('Bot Core Status: Ready!')
#

the connection var is my database

#

and all that works fine

#

then it detects my bot code as apart of the database

#

nope

pale turtle
#

Um you set the variable name of the db to client

#

And than do client.event

near sedge
#

o 💀

slate swan
near sedge
#

i've spent 40 mins on a damn simple error

#

thank you all fr

#

yep...

honest vessel
#

how can bot change a members nick?

#

i only find permissions check

#

should be like edit_member(nick="poop")

final iron
#

!d discord.Member.edit

unkempt canyonBOT
#

await edit(*, nick=..., mute=..., deafen=..., suppress=..., roles=..., voice_channel=..., reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Edits the member’s data.

Depending on the parameter passed, this requires different permissions listed below...
final iron
#

^ @honest vessel

honest vessel
#

yeah i found it but now this

#

Command raised an exception: Forbidden: 403 Forbidden (error code: 50013): Missing Permissions

#

bot has manage nickname on

#

in roles

cloud dawn
honest vessel
#

await user.edit(nick=str(user.display_name)+str(" (afk)"))

final iron
honest vessel
cloud dawn
#

Role of the member higher than the bots?

final iron
#

^

honest vessel
#

nah bot is admin and higher

#

bot has all permes checked

cloud dawn
honest vessel
#

yes

#

<disnake.interactions.application_command.ApplicationCommandInteraction object at 0x7f30b6de9580>
Command raised an exception: Forbidden: 403 Forbidden (error code: 50013): Missing Permissions

final iron
honest vessel
#

member object

#

should i do fetch_user?

#

maybe

final iron
#

No

honest vessel
#

but it should say has no agttribute this is about permissions

#

permissions are fine

final iron
#

Can you invite an alt to your server and try your command on it?

#

Or anyone with no roles/only member role

honest vessel
#

@final ironu got a point but

#

I can say bot has all perms, ON

#

and top of heriarchy

#

yet permission fails

#

bot itself intents = disnake.Intents.all() intents.guilds = True intents.members = True intents.presences = True intents.typing = True codewise

slate swan
#

You know that inter.author is already a union of Member and User right? This means you don't need fetch_member at all.

honest vessel
#

anything i need to activate on dev.discord?

#

@slate swanok but that we can fix later 😄

#

whatsup with the permissions

slate swan
#

Bot has no permissions

honest vessel
#

it has all

slate swan
#

You can say whatever you want, the API doesn't lie

honest vessel
#

and top of line

#

is there anything i need to do on discord dev portal?

slate swan
#

Nope

honest vessel
#

then wtf

final iron
#

As I said above, invite an alt and try it

honest vessel
#

ama do a dumbie function just change nick n see

slate swan
#

Well, you're trying to nick yourself right?

honest vessel
#

i am trying to use slash command and bot is supposed to change my nick

slate swan
#

And you probably have the server ownership right?

honest vessel
#

oh maybe i am higher than bot

#

cause owner atm

slate swan
#

Server ownership is bigger than everything

honest vessel
#

yeah

#

now the coin went down

slate swan
#

Bot can't nickname an owner, so there you go :p

honest vessel
#

i thought bot was owner

#

ama pass it over n test

#

🙂

slate swan
honest vessel
#

i forgot tho how i pass owner

#

maybe rightclick on bot?

slate swan
#

You can't pass to a bot

honest vessel
#

oh

#

ok ok then i do like i did before

#

let bot create a server

#

cause they can

slate swan
#

Only a limited amount, yeah

honest vessel
#

yeah i just need 1 server so

#

not public bot

#

Thanks guys helping my brain 😄

slate swan
#

how could i make a command that will make the channel nsfw

#

!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
#

Set the nsfw kwarg to True.

honest vessel
#

like ctx.channel.edit(nsfw=True)

#

or if ctx.message.channel

slate swan
#

You also need to await it since it's a coroutine

honest vessel
#

and put decoration on that command with has_permissions()

#

also check if it already is true, if it is dosame but put False

#

n u got a switch

slate swan
#
@bot.command()
async def nsfw(ctx):
    await ctx.channel.edit(nsfw=True)```
#

like that?

honest vessel
#

ye

#

that will turn all channels possible for nsfw tho

#

if one see u type that they can type it in another chan

#

n change chanperms

#
@commands.command(aliases=["ub"])
@commands.has_permissions(ban_members=True)
async def unban():
   pass #un-ban 
``` this has a permission check if the poster "author" has bermissions of ban users (not bots permissions)
outer violet
#

Anyone know how to use hikari?

forest blade
#

I personally have not even looked at it. This video may be good. https://youtu.be/xc1VpbRd4is

In this video, we go over the basic setup steps for creating a discord bot in python.

Let me know in the comments what videos you want to see next.

INSTALL PYTHON: https://www.python.org/downloads/
DISCORD DEVELOPER PORTAL: https://discord.com/developers/

HIKARI GITHUB: https://github.com/hikari-py/hikari/
HIKARI DOCUMENTATION: https://www.hi...

▶ Play video
quaint epoch
#

hey anyone know the installation for pycord?

#

bc i need to know the proper command so i don't install the wrong one

#

!pypi pycord

unkempt canyonBOT
little ether
velvet tinsel
quaint epoch
velvet tinsel
quaint epoch
velvet tinsel
#

!pypi disnake

unkempt canyonBOT
velvet tinsel
#

this

slim ibex
#

!pypi nextcord

unkempt canyonBOT
slim ibex
#

this

#

!pypi pincer

unkempt canyonBOT
slim ibex
#

or that

#

Pincer is in alpha but very promising

cold sonnet
#

Discord API wrapper rebuild from scratch.

slim ibex
#

true lmao

slim whale
#

datetime.datetime.utcnow.replace(microsecond=0)
#
File "main.py", line 77, in on_member_remove
    await channel.send(f":outbox_tray: [{datetime.datetime.utcnow.replace(microsecond=0)}] **{member}** ({member.id}) ha salido del servidor")
AttributeError: 'builtin_function_or_method' object has no attribute 'replace'```
#

why do i get this?

little ether
slim whale
#

so only datetime.datetime.utcnow()

little ether
honest vessel
#

lol at all diffrent forks

#

n one from scratch

kindred drum
#

yo ```py
await channel_admin.send(embed=verificationAdmin)
msg = await channel_admin.send(embed=verificationAdmin)

                                    await msg.add_reaction("❌")
                                    await msg.add_reaction("✅")``` produces this error 
In name: Must be between 1 and 100 in length.```
#

anyone got an idea why

#

its all indented properly

quaint epoch
#

not for me

kindred drum
quaint epoch
kindred drum
#

done

quaint epoch
#

which line is the error in?

#

and can you send the whole function?

kindred drum
#
 @commands.command(name="finish")
    async def finish(self, ctx):
        for i in range(0,len(Json_Items)): #It doesn't exist
            for x in Json_Items[i]:
                if int(x) == int(ctx.message.author.id):
                    if len(Json_Items[i][x]["User IGN"]) > 0:
                        if len(Json_Items[i][x]["Ps"]) > 0:
                            Json_Items[i][x]["user_verification"] = True
                            json.dump(Json_Items, open("./all_user_rep.json", "w"), indent=1)

                                        
quaint epoch
kindred drum
#
json.dump(Json_Items, open("./all_user_rep.json", "w"), indent=1)
                            for guild in bot.guilds:
                                for channel in guild.text_channels:
                                    
                                    if str(ctx.author.id) in str(channel.name):
                                        
                                        verification = discord.Embed(title = "Verification", description = ctx.author.mention, color = discord.Color.green())
                                        await ctx.channel.purge()
                                        ign = Json_Items[i][x]["User IGN"]
                                        verification.add_field(name = "ID", value = ctx.author.id, inline = True)
                                        verification.add_field(name = "IGN", value = ign, inline = False)
                                        paymentMethods = ' | '.join(Json_Items[i][x]["Ps"])
                                        verification.add_field(name = "P M", value = paymentMethods, inline = False)
                                        verification.add_field(name = "STATUS", value = "Completed")
                                        await ctx.channel.set_permissions(ctx.guild.default_role, send_messages=False)
                                        await ctx.send(embed=verification)
                                        await channel.edit(name=f"{ctx.author.name}-Completed-{channel.name}")
                                        await ctx.channel.send("This channel has been **archived** and is waiting on judgement from our <@&915363576867344435>")```
quaint epoch
#

alr

kindred drum
#
channel_admin = bot.get_channel(928357998559105095)
                                        verificationAdmin = discord.Embed(title = "Verification", description = ctx.author.mention, color = discord.Color.dark_red())
                                        verificationAdmin.add_field(name = "ID", value = ctx.author.id, inline = True)
                                        verificationAdmin.add_field(name = "IGN", value = ign, inline = False)
                                        paymentMethods = ' | '.join(Json_Items[i][x]["Ps"])
                                        verificationAdmin.add_field(name = "P M", value = paymentMethods, inline = False)
                                        verificationAdmin.add_field(name = "STATUS", value = "Waiting")
                                        await channel_admin.send(embed=verificationAdmin)
                                        msg = await channel_admin.send(embed=verificationAdmin)
        
                                        await msg.add_reaction("❌")
                                        await msg.add_reaction("✅")```
#

there

#

any idea?

quaint epoch
#

brb

kindred drum
#

😭

haughty quartz
#

how do you make server only commands

velvet tinsel
velvet tinsel
cloud dawn
unkempt canyonBOT
#

@disnake.ext.commands.guild_only()```
A [`check()`](https://docs.disnake.dev/en/latest/ext/commands/api.html#disnake.ext.commands.check "disnake.ext.commands.check") that indicates this command must only be used in a guild context only. Basically, no private messages are allowed when using the command.

This check raises a special exception, [`NoPrivateMessage`](https://docs.disnake.dev/en/latest/ext/commands/api.html#disnake.ext.commands.NoPrivateMessage "disnake.ext.commands.NoPrivateMessage") that is inherited from [`CheckFailure`](https://docs.disnake.dev/en/latest/ext/commands/api.html#disnake.ext.commands.CheckFailure "disnake.ext.commands.CheckFailure").
haughty quartz
#

okay, thanks :)

velvet tinsel
#

ok

cloud dawn
velvet tinsel
#

imo I dont like hot chocolate

haughty quartz
#

what is disnake tho?

velvet tinsel
haughty quartz
slate swan
haughty quartz
#

the .guild_permissions

slate swan
#

Ig

velvet tinsel
cloud dawn
haughty quartz
#

guild.only

kindred drum
velvet tinsel
#

replace anything to do with discord with disnake

haughty quartz
#

thanks guys

cloud dawn
kindred drum
slate swan
#

🤔

cloud dawn
#

Using motor you can make it async.

haughty quartz
kindred drum
#

I have not

haughty quartz
#

anyone here knows how to make bots work in threads?

cloud dawn
velvet tinsel
haughty quartz
cloud dawn
haughty quartz
#

do i just have to add guild = "guild id" up in my code?

haughty quartz
cloud dawn
kindred drum
haughty quartz
kindred drum
#
In name: Must be between 1 and 100 in length```
cloud dawn
haughty quartz
#

okay

cloud dawn
#

!d disnake.Guild.threads

unkempt canyonBOT
#

property threads: List[disnake.threads.Thread]```
A list of threads that you have permission to view.

New in version 2.0.
haughty quartz
#

oooo

#

nice ill look into it

cloud dawn
#

Do recommend using it.

haughty quartz
#

yeah ill probably change to disnake

cloud dawn
#

Awesome :)

little ether
#

try user.avatar.url

haughty quartz
# cloud dawn Awesome :)

hey so i gotta make a bot only allow messages in a certain channel that start with the command prefix(!) + qna , if the message does not, the bot will delete that message pls help

little ether
#

!d discord.Member.avatar

unkempt canyonBOT
#

property avatar```
Equivalent to [`User.avatar`](https://discordpy.readthedocs.io/en/master/api.html#discord.User.avatar "discord.User.avatar")
haughty quartz
little ether
#

its not a method btw, its a property

haughty quartz
#

i was thinking about msg.startswith("qna")

stray thistle
#

yeah

sick birch
#

It sort of acts as a gate to your command handlers

stray thistle
#

And else: await ctx.message.delete()

sick birch
#

If you do not process_commands() at the end of on_message, then that command will be ignored

#

You can use that to your advantage

#

By dictating what messages get processed and what are ignored

haughty quartz
#

how would dictate what messages get processed?

stray thistle
#

with .startswith

#

i guess

sick birch
haughty quartz
#

py@bot.event async def on_message(msg): if channel.id == 928397708149030923: if msg.content.startswith("qna"): print(works!) ? like that

sick birch
#

sure that would work but none of your commands would work

#

You'd need to process_commands()

haughty quartz
#

okay

#

@unborn prairie.commands?

#

sorry for the ping lol

stray thistle
#

can’t he just use commands instead of events ?

sick birch
#

on_message is the first thing that's called before any commands are processed, so you can do some funky things like editing the message.content. This way d.py thinks you sent one thing while in reality you sent something else.

#

Same concept with picking which messages progress to the command handling portion and which are ignored

#

You can drop the message before d.py even realizes that there is a message

haughty quartz
#

@sick birch could you give me a example? please

little ether
#

yeah, that would help

sick birch
#

on_member_join provides you with discord.Member, not discord.User

haughty quartz
sick birch
#

No, an event

haughty quartz
little ether
#
data = user.avatar.read()

here try this
user.avatar returns a Asset obj and it has an inbuilt .read method

sick birch
#

Why the spoonfeed

#

i can almost hear you selecting all and copying it lmao

#

Also there's really no need for .resize or any imaging libraries

#

d.py provides a native method to get the url in a certain format

haughty quartz
sick birch
#

not really

#

just the if statement

#

without the is True part

haughty quartz
sick birch
#

as long as you have process_commands()

#

also i suggest you refer to the documentation for that as you've got it wrong

#

also msg.startswith() will not working considering msg is of type discord.Message, not string

haughty quartz
#

yeah i should probably do that

sick birch
#

you got it

little ether
#

you could use user.avatar.with_size(size).read(), as robin said

cloud dawn
haughty quartz
cloud dawn
#

!d discord.ext.commands.Bot

unkempt canyonBOT
#

class discord.ext.commands.Bot(command_prefix, help_command=<default-help-command>, description=None, **options)```
Represents a discord bot.

This class is a subclass of [`discord.Client`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client "discord.Client") and as a result anything that you can do with a [`discord.Client`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client "discord.Client") you can do with this bot.

This class also subclasses [`GroupMixin`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.GroupMixin "discord.ext.commands.GroupMixin") to provide the functionality to manage commands.
haughty quartz
cloud dawn
sick birch
#

That's not how it works

cloud dawn
sick birch
#

process_commands actually starts up the command handler

#

It starts up the process where it figures out which command you called, which function to call, parsing args, etc...

#

How? It's just a coro

haughty quartz
#

bot = commands.Bot(command_prefix="!")

haughty quartz
sick birch
#

No it does not send anything

#

It only starts up the command handler

#

Without it none of your commands will work

cloud dawn
# haughty quartz sure

So you can also just do this ```py
@bot.command(name='test')
async def test_cmd(self, ctx):
if ctx.message.channel == 895072295146651709:
await ctx.send('Hello!')
else:
await ctx.send("Wrong channel!")

#

!test will trigger this command then.

sick birch
#

Yeah but they only want those commands to work in a certain channel

cloud dawn
sick birch
#

You could

#

But I find on_message() easier

haughty quartz
sick birch
#

But if you want to have a global check you can do that as well

cloud dawn
haughty quartz
#
@bot.event
async def on_message(msg):
    if msg.channel.id == 895072295146651709:
      if msg.content.startswith("qna"):
        print("qna message!")
      print("is in correct channel")
      await process_commands()(msg)
    else:```
sick birch
#

Not quite

haughty quartz
#

hm

#

yeah cause theres a error

sick birch
#

process_commands() takes one argument, the message instance

#

it's not a function that returns a function

#

I would strongly suggest you learn asyncio and the basics of python

cloud dawn
sick birch
#

Pretty sure you have to pass it?

#

Was it a bug or

cloud dawn
#

He uses msg instead of message

haughty quartz
cloud dawn
#
@bot.command(name='test')
async def test_cmd(self, ctx):
    if ctx.message.channel == 895072295146651709:
        await ctx.send('Hello!')
    else:
        await ctx.send("Wrong channel!")
sick birch
#

Oh no you just have to pass in the message instance

sick birch
#

You'd have to do that in every single command you have

#

Which in a larger scale could get quite painful

cloud dawn
sick birch
#

But like he said you can either do a global check or on_message()

haughty quartz
#

global check?

#

how

sick birch
#

global checks are more flexible

#

but for this case an on_message() will do unless you want to be fancy

cloud dawn
sick birch
#

There's really no advantage of using one over the other in this instance that I can think off the top of my head

#

But on_message() only works for filtering what messages get passed through, global checks are much more flexible

#

For example they can check who sent the message, etc...

haughty quartz
#

i give up lmao my 2 braincells cant comprehend this

cloud dawn
#

Or 4

stray thistle
#

Maximum 5 for the luckiests

pliant compass
#

I'm making a bot and I need it to get the last image that was sent in the chat. How can I do this?

sick birch
#

discord.py is not a beginner's library by any means

#

a firm understanding of the language is strongly recommended before diving in with the library

cloud dawn
#

Only if you would have some kind of cap.

sick birch
pliant compass
cloud dawn
pliant compass
#

Ok

cloud dawn
#

redis :D

sick birch
#

Why

#

a simple variable will do

cloud dawn
sick birch
#

i suppose

#

i never pass up an opportunity to gain a brain cell 😉

#

(learn redis)

slate swan
#

you guys have braincells?

haughty quartz
slate swan
cold sonnet
#

huh

cold sonnet
#

you used bot.command() yet used the self param

#

I couldn't hold myself back from pikaing you

#

here you go lemon_pika

slate swan
#

for a message one quote and then for the other two quotes?

cold sonnet
#

wat

#

oh

#

yes, weird

#

and

#

if ctx.message.channel == int_object:

#

is freaking me out

#

@cloud dawn you can't keep that message like that

cloud dawn
#

@haughty quartz```py
@bot.command(name='test')
async def test_cmd(ctx):
if ctx.channel.id == 895072295146651709:
await ctx.send('Hello!')
else:
await ctx.send("Wrong channel!")

#

@haughty quartzAll commands or just !test?

worldly bane
#

where is your bot.event since you can stop it there

cold sonnet
#

no the self is still there

cloud dawn
#
from discord import Message

@bot.listen()
async def on_message(message: Message) -> None:
    if message.author.bot:
        return

    if message.channel.id == 895072295146651709:
        if all([
            message.content.split(' ')[0][0] in bot.command_prefix,
            message.content.split(' ')[0][1:] in [cmd.name for cmd in bot.commands]
            ])
            await message.delete()
cold sonnet
#

wait what does -> None mean

cloud dawn
#

Habit

#

I could shorten it but i want to satisfy other programmers and readability.

sick birch
#

sort of like:

public static void myFunction() {

}
cold sonnet
#

so what if there's still a return something

sick birch
#

It doesn't matter

cold sonnet
#

it doesn't affect it

#

it's just a lie?

cloud dawn
sick birch
#

!e

def myFunc() -> str:
  return 5
print(myFunc())
unkempt canyonBOT
#

@sick birch :white_check_mark: Your eval job has completed with return code 0.

5
sick birch
#

¯_(ツ)_/¯

cold sonnet
#

lies

cloud dawn
sick birch
#

typehint is nothing more than a comment to python unless devs decide to take advantage of it

#

Typescript is much better in that aspect

cold sonnet
sick birch
#

stay mad

cloud dawn
cloud dawn
cloud dawn
cold sonnet
#

cog params in main file command

cloud dawn
#

I just thought he wanted something else

cold sonnet
#

once double quotes, once single quotes in send(), killing programming habits

#

it was a menace FeelsBadMan

pliant gulch
sick birch
#

true

#

i think typescript is strongly typed rather than statically typed

pliant gulch
#

Python can be strongly typed as well though

soft lynx
#

can i ask a question regarding slash commands here?

slate swan
#

are slash commands related to dpy and its forks?

cloud dawn
pliant gulch
#

Minecraft commands

cloud dawn
#

Hahaha yeah, i'm actually going to call it that now in my bot

cloud dawn
#
@commands.minecraft_command()
#

😂

slate swan
cloud dawn
#

If andy doesn't know the syntax the package most likely has no docs

slate swan
#

FR

pliant gulch
#

I don't even read docs?

#

I just source dive

cloud dawn
slate swan
#
await channel.send("text", file=kwarg)
pliant gulch
#

Like, for an example good luck on reading the source code of Qtile as pseudo documentation

cloud dawn
dim oriole
#

what was this thing that runs every specified time (seconds, minutes) like it runs every 30 seconds and does smth

slate swan
#

a task?

dim oriole
#

yea

#

thanks

slate swan
#

yw lol

dim oriole
#

how can i get a guild in a task like i need in for user in guild.users:

pliant gulch
#

Is it a specific guild?

dim oriole
#

yea

cloud dawn
#

But you can just do bot.guilds.

slate swan
#

yw

dim oriole
#

its just one guild i could specify with an id

pliant gulch
#

Yea

#

But you need to add wait_until_ready

#

Since tasks start before the cache is populated

dim oriole
#

where

pliant gulch
#

!d discord.ext.commands.Bot.wait_until_ready

unkempt canyonBOT
#

await wait_until_ready()```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Waits until the client’s internal cache is all ready.
pliant gulch
#

At the top of your task code

dim oriole
#

okay but how do i get a specified guild in a task

cloud dawn
#

smt like ```py
guild = [guild for guild in bot.guilds if 267624335836053506][0]

pliant gulch
#

bot.get_guild is faster

cloud dawn
#

#hardcoding

pliant gulch
#

Since it's dict getitem which is O(1)

cloud dawn
dim oriole
#

so bot.get_guild(id)

pliant gulch
#

Yes

dim oriole
#

thx

lapis breach
#

hey does any1 here knows how to use discord-components

#

... guess not

cloud dawn
#

Does that even get updated anymore?

slate swan
#

i would just use a fork tbh

cloud dawn
#

guess not xd

slate swan
#

dpy doesnt have timeout for members and it doesnt have buttons tbh just use a fork which is a full package

pliant gulch
#

It's archived isn't it

cloud dawn
pliant gulch
#

Kek

slate swan
#

oof

pliant gulch
#

Thank god, garbage library design

slate swan
cloud dawn
pliant gulch
#

They use the wait_for to hook onto button presses

lapis breach
pliant gulch
#

Meaning you can only wait for 1 in any command at a time

#

And if you want to wait for any amount you must spawn that many Futures

#

Since that's how wait_for works

cloud dawn
#

Only reading this hurts my soul

slate swan
#

gives me a stroke

pliant gulch
lapis breach
#

so... no1 can help me right?

slate swan
cloud dawn
#

disnakeeeee

lapis breach
cloud dawn
#

!pypi disnake

unkempt canyonBOT
cloud dawn
#

:)

slate swan
#

as shown above

lapis breach
# cloud dawn :)

i already got most of my code in the older version do i have to rewrite it?

cloud dawn
#

Jeez okimii giving them the scare

slate swan
#

but disnake gets maintained sooooooooooooooo

lapis breach
slate swan
pliant gulch
#

You'd change the namespace which you access models and methods from

#

discord -> disnake

slate swan
#

buttons are way different

#

i think

cloud dawn
slate swan
#

do they subclass view?

pliant gulch
#

Don't disnake's button use Views as well

cloud dawn
slate swan
pliant gulch
#

🙏

cloud dawn
slate swan
cloud dawn
#

Only 1 i gotta work tomorrow

slate swan
cloud dawn
#

I swear ;-;

lapis breach
slate swan
#

oof

lapis breach
#

i dont remember how i fixed that the other time

slate swan
cloud dawn
slate swan
#

so many ways lol

lapis breach
#

k thx

cloud dawn
#

Think python is used for <3.10

#

3.10 uses py

#

Atleast in my env lol

slate swan
cloud dawn
slate swan
#

for me 2.7 uses python and 3.9 uses python3
You can alias it

lapis breach
#

wait... i installed this on a project witch has discord.py.... is this a problem?

cloud dawn
#

I got 2 python instance.

slate swan
lapis breach
pliant gulch
#

I did doas pacman -Syu and it updated my python to 3.10 😔

#

I wasn't ready to switch

slate swan
#

i havent updated cuz pylance has a stroke with 3.10

cloud dawn
slate swan
#

python 3.10's pip installation on Ubuntu was broken on the earlier release lol

pliant gulch
#

Just don't get disnake and discord mixed up

lapis breach
#

should i change anything on my imports?

slate swan
pliant gulch
cloud dawn
slate swan
#

or just install Disnake as Discord

slate swan
#

In your venv

cloud dawn
slate swan
pliant gulch
#

Kali?

#

👁️ 👁️

small igloo
#

how to get information from API :v i forgor

cloud dawn
slate swan
slate swan
pliant gulch
#

Kali as a daily driver??

#

😖

slate swan
small igloo
slate swan
#

and I don't need to do anything too windowish

pliant gulch
#

Either way you can just setup a KVM with GPU passthrough running windows on redhat drivers

slate swan
slate swan
small igloo
slate swan
#

!d aiohttp

#

wait

small igloo
#

k

slate swan
cloud dawn
slate swan
small igloo
small igloo
slate swan
#

Ah

slate swan
# small igloo smol
async​ ​with​ ​aiohttp.ClientSession​() ​as​ ​session​: 
 ​            ​res​ ​=​ ​await​ ​session​.​get​(​"url"​) 
 ​            ​json_data​ ​=​ ​await​ ​res​.​json​()
slate swan
#

Well , just import aiohttp, u don't need to install it
It's installed with discord.py

slate swan
#

Why import json

small igloo
pliant gulch
#

It's a dict, you access the key

small igloo
small igloo