#discord-bots

1 messages Β· Page 161 of 1

slate swan
#

oh ok thanks

cold sonnet
#

you can use bot.guilds in the command

primal token
#

it isn't internally ready*

slate swan
#

the bot is ignoring the commands

#

yeah no not how python works

#

you need to acess the guild attribute of a discord.Member instance, not the class

slate swan
#

i used discord.Member.guild

#

i changed it to bot.guilds cus u said i could

#

@slate swan anyways my bot is not responding to any command, he is going online but not responding to any command

unkempt canyonBOT
#

Using intents in discord.py

Intents are a feature of Discord that tells the gateway exactly which events to send your bot. Various features of discord.py rely on having particular intents enabled, further detailed in its documentation. Since discord.py v2.0.0, it has become mandatory for developers to explicitly define the values of these intents in their code.

There are standard and privileged intents. To use privileged intents like Presences, Server Members, and Message Content, you have to first enable them in the Discord Developer Portal. In there, go to the Bot page of your application, scroll down to the Privileged Gateway Intents section, and enable the privileged intents that you need. Standard intents can be used without any changes in the developer portal.

Afterwards in your code, you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:

from discord import Intents
from discord.ext import commands

# Enable all standard intents and message content
# (prefix commands generally require message content)
intents = Intents.default()
intents.message_content = True

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

For more info about using intents, see discord.py's related guide, and for general information about them, see the Discord developer documentation on intents.

slate swan
#

enable message_content intents and please do read the complete paragraph above

#

alright thank you

#

how can i delete the active server invite links? i can't find a solution

naive briar
#

!d discord.Guild.invites

unkempt canyonBOT
#

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

Returns a list of all active instant invites from the guild.

You must have [`manage_guild`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_guild "discord.Permissions.manage_guild") to get this information.
naive briar
#

!d discord.Invite.delete

unkempt canyonBOT
#

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

Revokes the instant invite.

You must have [`manage_channels`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_channels "discord.Permissions.manage_channels") to do this.
slate swan
#

module 'discord.invite' has no attribute 'delete'

naive briar
#

Send your code as text

#

!code

unkempt canyonBOT
#

Here's how to format Python code on Discord:

```py
print('Hello world!')
```

These are backticks, not quotes. Check this out if you can't find the backtick key.

naive briar
#

And you need an instance, not a class

slate swan
#
@client.command()
async def rdai(ctx):
    await discord.invite.delete()
naive briar
#

Also discord.invite is a module not a class

slate swan
#

oh

#

so what do i need to do?

naive briar
#

Get the invites from a guild?

slate swan
#

to delete all the invite links

#

this is my code now and i'm getting this error
'member_descriptor' object has no attribute 'http'

naive briar
#

Send the code as text

#

I just said you need an instance, not a class

slate swan
#
import discord
from discord import Intents, Invite
from discord.ext import commands



intents = Intents.default()
intents.message_content = True

client = commands.Bot(command_prefix="!", intents=intents)


@client.event
async def on_ready():
    print('Online')


@client.command()
async def dai(ctx):
    await Invite.delete(self=Invite)
naive briar
#

This is way it is always recommended to know OOP before trying discord.py

slate swan
#

yeah i know i'm just trying to find a quick solution to something in my server that i'm stuck on

naive briar
#

It's just

guild = ctx.guild # get the guild
invites = await guild.invites() # get instances (objects) of invite class
#

Really?

slate swan
#

yeah

#

thank you i appreciate you help

somber sky
#

How come when I make a slash command it takes forever to register? I made th e command yesterday

naive briar
#

Did you sync the command tree

somber sky
#

I just made a sync command I forgot to

slate swan
#

is that it?

naive briar
#

Are you kidding me

#

The .invites method returns a list of invites

slate swan
#

i don't need the list

naive briar
#

You need to iterate over it then delete

slate swan
#

i don't know how to do that that's why i'm here

naive briar
#

You don't know how to use for in?

slate swan
#

i used to but i haven't touched python for like 2 years or so

steel mango
#

Guys is there a way for the discord bot to tell if a message contains a certain word

cloud dawn
#

!for-else

unkempt canyonBOT
#

for-else

In Python it's possible to attach an else clause to a for loop. The code under the else block will be run when the iterable is exhausted (there are no more items to iterate over). Code within the else block will not run if the loop is broken out using break.

Here's an example of its usage:

numbers = [1, 3, 5, 7, 9, 11]

for number in numbers:
    if number % 2 == 0:
        print(f"Found an even number: {number}")
        break
    print(f"{number} is odd.")
else:
    print("All numbers are odd. How odd.")

Try running this example but with an even number in the list, see how the output changes as you do so.

naive briar
#

I don't know what to say ducky_regal

naive briar
unkempt canyonBOT
#

@naive briar :white_check_mark: Your 3.11 eval job has completed with return code 0.

001 | 1
002 | 4
003 | 9
004 | 16
shrewd fjord
#

wait a sec

#

is that like power square? @naive briar

naive briar
#

Idk, just throwing stuff around

slate swan
shrewd fjord
#

oh xd

#

4*4 = 16

#

kinda makes sense

#

4^2 = 16 too xd

shrewd fjord
steel mango
#

I tried that before asking but it didn't work

slate swan
# shrewd fjord ?

I tried to use this command in order to delete all server invite links but it isn't working

steel mango
#

I'll try again

shrewd fjord
steel mango
#

Wasn't giving an error

#

It just didn't work

#

It looked correct syntax wise

cloud dawn
maiden fable
#

πŸ‘€

somber sky
#

is there another way to sync my slash commands without using the sync command

#

I just added sync command so I csnt sync it

#

It’s been a whole day since I made these commands

cloud dawn
#

I just sync it to one guild in the setup_hook then have a command for syncing globally.

unkempt canyonBOT
shrewd fjord
spiral spoke
#
import discord
import json
from discord.ext import tasks
import random
import datetime

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

client = discord.Client(intents=intents)


# Load the JSON file
try:
    with open('messages.json') as f:
        messages = json.load(f)
except Exception as e:
    print(f'An error occurred while opening the messages.json file: {e}')

@tasks.loop(time=datetime.time(hour=18, minute=10))
async def send_message():
    try:
        # Choose a random message from the list
        message = random.choice(messages)

        # Replace 'channel_id' with the ID of the channel you want to send the message to
        channel = client.get_channel(1040599108408311859)
        await channel.send(message)
    except Exception as e:
        print(f'An error occurred while sending the message: {e}')

@client.event
async def on_ready():
    send_message.start()

# Replace 'token' with your Discord bot's token
client.run('')

I'm trying to make a discord bot with discord.py, the bot should send an automatic message every day at a specific time and minutes from a json file, but it doesn't send anything, nor does it show errors in the console, can someone help me ?

cloud dawn
shrewd fjord
#

πŸ˜‚

cloud dawn
cloud dawn
# spiral spoke ```py import discord import json from discord.ext import tasks import random imp...
from datetime import datetime

from discord.ext import tasks
from discord.ext.commands import Bot, Cog

class MyCog(Cog):
    def __init__(self, bot: Bot) -> None:
        self.bot = bot
        self.weather_loop.change_interval(time=self.get_next_date_at(hours=6))
        self.weather_loop.start()

    async def cog_unload(self) -> None:
        self.printer.cancel()

    def get_next_date_at(*, hours: int = 0, minutes: int = 0, seconds: int = 0) -> datetime:
        dtnow = datetime.now()
        if dtnow.hour < hours or dtnow.minute < minutes or dtnow.second < seconds:
            dt = datetime(dtnow.year, dtnow.month, dtnow.day, hours, minutes, 0, 0)
        else:
            tomorrow = dtnow + timedelta(days=1)
            dt = datetime(tomorrow.year, tomorrow.month, tomorrow.day, hours, minutes, 0, 0)

        return dt

    @printer.before_loop
    async def before_weather_loop(self) -> None:
        await self.bot.wait_until_ready()

    @tasks.loop()
    async def weather_loop(self) -> None:
        ...

    @bulker.after_loop
    async def after_weather_loop(self) -> None:
        self.weather_loop.change_interval(time=self.get_next_date_at(hours=6))
``` I tackled it like this, this is an example tough.
shrewd fjord
#

zamn

cloud dawn
#

But agreed I don't get why it isn't some kind of kwarg for it.

spiral spoke
cloud dawn
#

You can pass a datetime but you cannot make it recurring.

slate swan
#

!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/latest/ext/tasks/index.html#discord.ext.tasks.Loop "discord.ext.tasks.Loop").
cloud dawn
slate swan
#

the time kwarg

spiral spoke
slate swan
#

what do i type here?

cloud dawn
slate swan
maiden fable
#

@cloud dawn you forgot to help Wolt πŸ‘€

cloud dawn
maiden fable
#

Lmao its fun, downloaded it just today (I am sure I will get bored in a day tho)

cloud dawn
#

"its fun" you haven't played ow1 lol

maiden fable
#

Prolly

cloud dawn
steel mango
#

how do i get my bot to add 2 different reactions to one message?

maiden fable
#

!d discord.Message.add_reaction

unkempt canyonBOT
#

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

Adds a reaction to the message.

The emoji may be a unicode emoji or a custom guild [`Emoji`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Emoji "discord.Emoji").

You must have [`read_message_history`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.read_message_history "discord.Permissions.read_message_history") to do this. If nobody else has reacted to the message using this emoji, [`add_reactions`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.add_reactions "discord.Permissions.add_reactions") is required.

Changed in version 2.0: `emoji` parameter is now positional-only.

Changed in version 2.0: This function will now raise [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError "(in Python v3.11)") instead of `InvalidArgument`.
steel mango
#

well ive got that much to add one reaction

slate swan
#

well do it again for 2 reactions?

steel mango
#

it doesnt react to same message then

#

nvm got it working

#

i had an "and" in there

slate swan
#

await integration.delete(reason="AntiBot")

error : forbidden

#

2022-12-21 180010 ERROR discord.client Ignoring exception in on_integration_create
Traceback (most recent call last):
File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 409, in _run_event
await coro(*args, **kwargs)
File "C:\Users\user\Desktop\Other\Bots_For_Sell\Sys+Tick\bot.py", line 69, in on_integration_create
await integration.delete(reason="AntiBot")
File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\integrations.py", line 153, in delete
await self._state.http.delete_integration(self.guild.id, self.id, reason=reason)
File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\http.py", line 738, in request
raise Forbidden(response, data)
discord.errors.Forbidden: 403 Forbidden (error code: 50001): Missing Access

maiden fable
#

You don't have perms prolly

fair shuttle
#

i got this message everytime im kinda new to codding tho so i js want to know why i got this

fair shuttle
#

oh

#

lmfao im stupid

slate swan
#
import discord
from discord import Guild, Intents, Invite
from discord.ext import commands



intents = Intents.default()
intents.message_content = True

client = commands.Bot(command_prefix="!", intents=intents)



@client.event
async def on_ready():
    print('Online')


        
@client.command()
async def dai(ctx):
    for invite in discord.Guild.invites:
        await invite.delete```
my goal is to delete all the active invite links and this is not working
vocal snow
#

you need to call invite.delete

slate swan
#

how do i do that? can you send an example?

vocal snow
#

have you used functions

slate swan
#

nope

cloud dawn
slate swan
#

i don't have experience with functions that's what i mean

#

i haven't used functions before

vocal snow
#

you should learn them then

#

you've used them plenty of times in the code you've sent

slate swan
#

do you mean the for in?

#

and async def?

cloud dawn
#

Do some research about methods (functions), class and OOP. @slate swan
If we're explaining something we'd at least expect some knowledge of the Python language.

slate swan
#

alright i will but i just need this code immediately, can you maybe solve this one for me?

cloud dawn
#

In this Python Object-Oriented Tutorial, we will begin our series by learning how to create and use classes within Python. Classes allow us to logically group our data and functions in a way that is easy to reuse and also easy to build upon if need be. Let's get started.

Python OOP 1 - Classes and Instances - https://youtu.be/ZDa-Z5JzLYM
Python...

β–Ά Play video
#

Amazing tutorial about OOP and classes, it also uses and mentions functions.

bright wedge
#

#bot-commands

steel mango
#

how do i get user inputs for a bot command?

#

and is there a way to store that input?

vocal snow
#

a user input in what way?

steel mango
#

like a command to do maths calculations

vocal snow
#
!command argument1 argument2
``` do you want to get the arguments?
steel mango
#

yeah thats what i meant

vocal snow
#

if you're using discord.py the commands extension makes this easy for you

steel mango
#

alr thanks

feral frost
#

i get this error with my slash command bot it started like 15 minutes ago what do i do ?

#

i tried resetting the token

#

restarting the bot

#

but nothing works

cloud dawn
#

What command?

fading marlin
#

your command's signature is not synced with what discord has

somber imp
wide whale
#

i require the doingening of this (yeet a command into a subgroup or w/e it's called)

#

unfortunately

fading marlin
blissful lagoon
#

please don't use ableist language

cloud dawn
winged coral
#

Do we not?

wide whale
wide whale
cloud dawn
#

Correction- could possibly play.

wide whale
#

rn i just want the basics

feral frost
wide whale
severe mural
#

error said: discord.app_commands.errors.CommandInvokeError: Command 'suggest' raised an exception: NotFound: 404 Not Found (error code: 10015): Unknown Webhook

wide whale
#

so thanks

fading marlin
#

you're editing a response without actually responding to the interaction

severe mural
#

please solution x.x

fading marlin
#

!d discord.InteractionResponse - you have to respond to the interaction using any of these methods

unkempt canyonBOT
#

class discord.InteractionResponse```
Represents a Discord interaction response.

This type can be accessed through [`Interaction.response`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Interaction.response "discord.Interaction.response").

New in version 2.0.
slate swan
#

Just defer if you're only trying to edit an already-existing message

severe mural
#

ah think there is " im = await interaction.send('Do you want upload image?, or say "N" to skip')"

#

.send change is send.response? or response.send_message?

#

bruh.

slate swan
#

Btw does anyone know what is meant on the dpy docs by "a traditional avatar" under User.avatar?

"If the user does not have a traditional avatar, None is returned."

severe mural
fading marlin
#

sure

severe mural
#

and alrleady change fix, my forget no i dea.

severe mural
severe mural
fading marlin
#

wut

severe mural
#

._.

slate swan
fading marlin
#

no, default avatars are traditional avatars

sick birch
somber sky
#

How would I do that

slate swan
#

The same way you'd normally make a dictionary in Python probably

fading marlin
#

discord?

slate swan
#

🀨

fading marlin
#

are you talking about discord.utils?

maiden fable
#

from discord import utils?

somber sky
#

Command 'alertschannel' raised an exception: OperationalError: no such column: alertschannel

@client.tree.command(description='Set Alerts Channel.')
@commands.has_permissions(administrator=True)
async def alertschannel(ctx, channel: discord.TextChannel):

    channel = channel.id

    async with aiosqlite.connect("main.db") as db:
      async with db.cursor() as cursor:
        await cursor.execute('UPDATE users SET alertschannel= ? WHERE guild = ?', (channel, ctx.guild.id,))
        pr = discord.Embed(title="Alerts Channel Set", description=f'Alerts channel has been set to <#{channel}>')              
        await ctx.response.send_message(embed=pr)
      await db.commit()```
#

im so confused why it isnt working

#
@client.tree.command(description='Must use this command to set channels.')
@commands.has_permissions(administrator=True)
async def setup(ctx):
  async with aiosqlite.connect("main.db") as db:
    async with db.cursor() as cursor:
      await cursor.execute('SELECT transactionschannel FROM users WHERE guild = ?', (ctx.guild.id,))
      data = await cursor.fetchone()
      if data:
        pass
      else:
        await ctx.send("Set everything up!")
        await cursor.execute('INSERT INTO users (transactionschannel, alertschannel, guild, demandchannel) VALUES (?, ?, ?, ?)', (0, ctx.guild.id, 0,))
    await db.commit()```
drifting arrow
#

So how do I edit a role?

fading marlin
#

!d discord.Role.edit

unkempt canyonBOT
#

await edit(*, name=..., permissions=..., colour=..., color=..., hoist=..., display_icon=..., mentionable=..., position=..., reason=...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Edits the role.

You must have [`manage_roles`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_roles "discord.Permissions.manage_roles") to do this.

All fields are optional.

Changed in version 1.4: Can now pass `int` to `colour` keyword-only parameter.

Changed in version 2.0: Edits are no longer in-place, the newly edited role is returned instead...
drifting arrow
sick birch
#

!d discord.app_commands.CommandTree.sync

fading marlin
#

no?

unkempt canyonBOT
#

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

Syncs the application commands to Discord.

This also runs the translator to get the translated strings necessary for feeding back into Discord.

This must be called for the application commands to show up.
drifting arrow
fading marlin
#

well, yeah, kinda, you gotta get the role somehow

sick birch
#

it'll probably be in your cache

fading marlin
#

not necessarily via fetching

#

heyo robin

somber sky
#
 helpem.set_author(name=f"{client.user}", icon_url=ctx.client.user.avatar.url)```

Why doesn't this work
azure tulip
#

why i see this problem?

rare echo
#

ctx.client.user.avatar.url pikaOMG

rare echo
azure tulip
#

thank u

#

hahaha ok what is it problem?

rare echo
rare echo
#

so just cd Bot

azure tulip
#

it not work

#

ohhh

rare echo
azure tulip
#

sorry,
I'm a moron

cloud dawn
#

What is the full path to hikisan

rare echo
cloud dawn
#

Yep

azure tulip
#

why does it not want to go to the bot folder?

#

ashjdhashdjahs nice

rare echo
#

you may just want to look into an IDE..

azure tulip
#

i don't have IDE

cloud dawn
#

I have no idea either

rare echo
#
cd /d "D:\Discord Bot\Hikisan\Bot"```
#

its a separate drive

azure tulip
rare echo
#

you turned off the light?

azure tulip
#

Me*

rare echo
#

what

#

where does "Me" go in that sentence

azure tulip
sick birch
#

i am mad confused

rare echo
oblique sorrel
#

Hello, I want to print some of my programs print statements inside my discord channel, I also want click able buttons to go to an url.
And i want to add data to my code through a slashcommand. Should I use a webhook, or a full on bot?

rare echo
#

bot

#

well, wait

#

you want to send a message of your print statements?

#

well slash commands and a webhook wouldnt work so well, so yes bot

oblique sorrel
#

my program prints some events

#

and I want to see those events in a discord channel

#

but I also want to append userinput to a file

#

"hello injections"

fair shuttle
#

can sm1 help me w that?

#

the code seem right

fading marlin
#

capital S

#

and don't use replit, nor change presences in on_ready

errant saddle
#

Im trying to use py to exe but every time i use it it keeps saying error

#

@fading marlin

#

there?

fair shuttle
rare echo
rare echo
fair shuttle
errant saddle
#

Na jk

#

But do u know how?

rare echo
rare echo
errant saddle
#

I'll take ss

sick birch
fair shuttle
#

like tht?

rare echo
errant saddle
slate swan
#

why do people have to use discord.py and google for discord.js code online

errant saddle
#

requirements already satisfied

slate swan
errant saddle
#

Talking 2 me

rare echo
#

yeah that was my next question, how are you trying to implement dpy to this

slate swan
#

it won't install the dependencies properly

fair shuttle
sick birch
fair shuttle
#

i have the commands.bot thing

unkempt canyonBOT
#

class discord.ext.commands.Bot(command_prefix, *, help_command=<default-help-command>, tree_cls=<class 'discord.app_commands.tree.CommandTree'>, description=None, intents, **options)```
Represents a Discord bot.

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

This class also subclasses [`GroupMixin`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.GroupMixin "discord.ext.commands.GroupMixin") to provide the functionality to manage commands.

Unlike [`discord.Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client"), this class does not require manually setting a [`CommandTree`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CommandTree "discord.app_commands.CommandTree") and is automatically set upon instantiating the class.

async with x Asynchronously initialises the bot and automatically cleans up.

New in version 2.0.
sick birch
#

well actually ignore that

#

!d discord.Client

unkempt canyonBOT
#

class discord.Client(*, intents, **options)```
Represents a client connection that connects to Discord. This class is used to interact with the Discord WebSocket and API.

async with x Asynchronously initialises the client and automatically cleans up.

New in version 2.0.

A number of options can be passed to the [`Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client").
sick birch
#

there are a lot of params so open up the docs link and look there

slate swan
errant saddle
slate swan
#

there's no builder.py file in the directory you are in

errant saddle
fair shuttle
#

why its in red if i did the site thing lol

errant saddle
#

no cmd window

#

option

slate swan
#

cd "path to your folder"

#

the path to your folder is in the top nav

rare echo
slate swan
#

also there's no point of packing a bot into an exe πŸ—Ώ

fair shuttle
errant saddle
rare echo
#

and eclipse grabber?...

#

like eclipse token grabber :|

rare echo
slate swan
#

πŸ—Ώ wow lol

fair shuttle
rare echo
slate swan
#

indentation man, and ctx is the first argument in all commands

fading marlin
#

ajsdflkj this one doesn't have it

#

!d discord.Client

unkempt canyonBOT
#

class discord.Client(*, intents, **options)```
Represents a client connection that connects to Discord. This class is used to interact with the Discord WebSocket and API.

async with x Asynchronously initialises the client and automatically cleans up.

New in version 2.0.

A number of options can be passed to the [`Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client").
fading marlin
#

there we go, see the status kwarg

slate swan
#

its under **options lol, you can read about it in the docs string tho

fading marlin
#

Bot doesn't explicitly mention it in as a parameter. You gotta check Client for it

fair shuttle
errant saddle
#

So

rare echo
#

no help with token stealers basically

rare echo
fair shuttle
#

alrr

#

first line or 2nd line i put it?

slate swan
#

why don't you just use the status arg in Bot

rare echo
#

alr,
first you need to async def {something}(ctx):

but as Lee was saying you can put it in constructor and avoid the command altogether

slate swan
#
bot = commands.Bot( stuff you have already, status = discord.Status.idle )
fading marlin
#

omg I had to reread the "stuff you have already" 4 times 😭

rare echo
slate swan
#

you might also want to lookup into indentation in python

rare echo
#

or the basics in general pikathink

slate swan
rare echo
#

lmao

#

stuffyoualreadyhave ping

fading marlin
#

I don't like this update though

#

reader function seems to be broken πŸ˜”

rare echo
#

welcome to the real world

slate swan
#

subclass braincells and make ur own implementation

rare echo
#

lmfao

fading marlin
#

idk how, I can't read!!

rare echo
#

thats a lot of sockets

slate swan
#

use rust :V

#

let the crabby read it for u

fading marlin
#

gotta learn it first ducky_australia

rare echo
#

rust that fun? need something new to learn

#

or is this like saying assembly is fun

slate swan
#

wouldn't say it's real fun, but yeah a nice language to learn. you won't particularly hate it

fading marlin
#

wasn't there a programming language called lolcode or something like that?

rare echo
#

brainf*ck

slate swan
#

yeah lolcode exists too

loud junco
#

me trying to find a free hosting server that has a database, less rate limits and unlimited total time usage πŸ₯Ή

slate swan
#

remove free or get a credit card

sick birch
rare echo
slate swan
somber sky
#

how do i add a time limit to a button

#

like, they have a certain amount of time till they cant click it anymore

fading marlin
#

!d discord.ui.View you add the timeout to the view

unkempt canyonBOT
#

class discord.ui.View(*, timeout=180.0)```
Represents a UI view.

This object must be inherited to create a UI within Discord.

New in version 2.0.
somber sky
#

thanks

somber sky
#
@client.tree.command(name='promote', description='Promote a player.')
@app_commands.choices(position=[
    app_commands.Choice(name="General Manager", value="General Manager"),
    app_commands.Choice(name="Head Coach", value="Head Coach"),
    ])
async def promote(i: discord.Interaction, user:discord.Member, position: app_commands.Choice[str]):
    GMRole = discord.utils.get(i.guild.roles, name="General Manager")
    HCRole = discord.utils.get(i.guild.roles, name="Head Coach")
    FORole = discord.utils.get(i.guild.roles, name="Franchise Owner")
    teams = discord.utils.find(lambda r: r.name in nflRoleListNames, i.user.roles)
    if any(role in FORole for role in i.user.roles):
      if any(role.name in nflRoleListNames for role in i.user.roles):
       if (position.value == 'General Manager'):
         await user.add_roles(GMRole)
       if (position.value == 'Head Coach'):
         await user.add_roles(HCRole)```

Im trying to make it where, if you have FORole, and and role name in nflRoleListNaames, then It'll give the role depending on which option you pick
#

its not working, How do I fix it?

#

discord.app_commands.errors.CommandInvokeError: Command 'promote' raised an exception: TypeError: argument of type 'Role' is not iterable

#

thats the error

unkempt canyonBOT
#

Please provide the full traceback for your exception in order to help us identify your issue.
While the last line of the error message tells us what kind of error you got,
the full traceback will tell us which line, and other critical information to solve your problem.
Please avoid screenshots so we can copy and paste parts of the message.

A full traceback could look like:

Traceback (most recent call last):
  File "my_file.py", line 5, in <module>
    add_three("6")
  File "my_file.py", line 2, in add_three
    a = num + 3
        ~~~~^~~
TypeError: can only concatenate str (not "int") to str

If the traceback is long, use our pastebin.

sick birch
somber sky
#

ngl i just chaanged a bunch of things and somehow got it to work

#

i ended up with this

#
@client.tree.command(name='promote', description='Promote a player.')
@app_commands.choices(position=[
    app_commands.Choice(name="General Manager", value="General Manager"),
    app_commands.Choice(name="Head Coach", value="Head Coach"),
    ])
async def promote(i: discord.Interaction, user:discord.Member, position: app_commands.Choice[str]):
    GMRole = discord.utils.get(i.guild.roles, name="General Manager")
    HCRole = discord.utils.get(i.guild.roles, name="Head Coach")
    FORole = discord.utils.get(i.guild.roles, name="Franchise Owner")
    teams = discord.utils.find(lambda r: r.name in nflRoleListNames, i.user.roles)
    teams2 = discord.utils.find(lambda r: r.name in nflRoleListNames, user.roles)
    if FORole not in i.user.roles:
     await i.response.send_message("You are not a Franchise Owner.", ephemeral=True)
    if teams not in user.roles:
      await i.response.send_message(f"User is not on your team.")
    else:
        if FORole in i.user.roles:
          if any(role.name in nflRoleListNames for role in user.roles):
           if (position.value == 'General Manager'):
             await user.add_roles(GMRole)
           if (position.value == 'Head Coach'):
             await user.add_roles(HCRole)```
#

works perfectly though

somber sky
sick birch
somber sky
#

thanks

somber sky
sick birch
#

To avoid nesting - you've got plenty going on already πŸ˜›

somber sky
#

i want it to not go through unless no one has the role on the team

#

examaple:

if team 1 already has a GM. then you cant give it to someone else. If the team doesn't have a GM then you can.

rare echo
#

i feel like this would have been easier from the get go if you started with data instead of using roles to check everything

waxen granite
#
    @tasks.loop(minutes= 30)
    async def statscounter(self):
        for key in self.serverstats.keys():
            guild = self.bot.get_guild(int(key))
            try:
                server_stats = self.serverstats[str(guild.id)]
            except KeyError:
                server_stats = {}
            category = discord.utils.get(guild.categories, name="STATS")
            botcount = 0
            membercount = 0
            members = guild.members
            textchannelscount = len(guild.text_channels)
            voicechannelscount = len(guild.voice_channels)
            for member in members:
                if member.bot == True:
                    botcount += 1
                else:
                    membercount += 1
            users_text = f"Users: {membercount}"
            bots_text = f"Bots: {botcount}"
            channels_text = f"Text Channels: {textchannelscount}"
            channels_voice = f"Voice Channels: {voicechannelscount}"
            tier = f"Premium Tier: Level {guild.premium_tier}"
            uc = guild.get_channel(server_stats['member_count'])
            bc = guild.get_channel(server_stats['bot_count'])
            tc = guild.get_channel(server_stats['text_count'])
            vc = guild.get_channel(server_stats['voice_count'])
            pt = guild.get_channel(server_stats['tier'])```
#
            if uc.name != users_text:
                await asyncio.sleep(1)
                await uc.edit(name=users_text, category=category)
            if bc.name != bots_text:
                await asyncio.sleep(1)
                await bc.edit(name=bots_text, category=category)
            if tc.name != channels_text:
                await asyncio.sleep(1)
                await tc.edit(name=channels_text, category=category)
            if vc.name != channels_voice:
                await asyncio.sleep(1)
                await vc.edit(name=channels_voice, category=category)
            if pt.name != tier:
                await asyncio.sleep(1)
                await pt.edit(name = tier, category=category)```
why wont this autoupdate every 30 mins?
somber sky
#

no clue how to do that though

severe field
#

somebody knows how command β€œs/text/text” work
It like replaces previous message

loud junco
#

railway.app only provides 21 days of free service per month ;-;

rare echo
#

old computers or a raspi go a long way

shrewd fjord
#

zamn

slate swan
vale wing
broken citrus
#

how to add buttons?

thick bolt
#

okay so I dont know how to do this, Im stuck. Anytime someone sends a message in my server which contains the word "VC" in it, then I want the bot to list all the VCs available in the channel and say something like "Perhaps you'd like to join one of these to hang out?" and then when you click on that UI VC, you should be able to join it

#
 @user.event
 async def on_message(message):
     if "vc" in str(message):
        discord.ui.ChannelSelect(channel_types=ChannelType.voice, placeholder="Which VC you wanna join?", min_values=1, max_values=1,disabled=False, row=None)
#

yeah so Im not doing this right uhhh

#

can someone help?

broken citrus
alpine cove
#

I think ChannelSelect is for slash command

thick bolt
alpine cove
#

just list all the links and hyperlink their jump url

thick bolt
#

oh I see, so what do I do then?

alpine cove
thick bolt
alpine cove
#

if vs in message.content:
for channel in message.channel.guild.voice_channels:
...

#

use list comprehension

thick bolt
#

is on_message not the right way to do it or

alpine cove
#

if vs in message.content:
voice_channels = "\n".join([f"{channel.name}" for channel in message.channel.guild.voice_channels])

alpine cove
thick bolt
alpine cove
#

on phone rn so its hard doing those long lines

alpine cove
thick bolt
#

I want the bot to be like "Yo these are your options"

slate swan
marble rampart
#

im trying to create a server/website that gets images from my java app in android studio then returns a url of the image (image to url) and it worked for me yesterday but now when i turn on replit it gives me this error: ```python
Traceback (most recent call last):
File "main.py", line 2, in <module>
from werkzeug.utils import secure_filenarme
ImportError: cannot import name 'secure_filenarme' from 'werkzeug.utils' (/home/runner/QrCodeApp-1/venv/lib/python3.8/site-packages/werkzeug/utils.py)

i tried everything but noting works anyone has any idea on how to fix this ?
thick bolt
# slate swan So options?

basically options that the user can then select and then after they select it, they would join whichever one they select

#

it should be pretty simple, I just dont understand how to do this

thick bolt
#

I think I should probably first watch some videos on this or something?

slate swan
#

O I got good video

thick bolt
#

I wanna be able to do wahtever I want, I just cant go through endless Documentation, this isnt working out

slate swan
vale wing
#

Bots can't connect users to voice chats

slate swan
vale wing
#

If you mean that

slate swan
#

Maybe you mean an invite with one use

#

To private vc

#

And use ephemeral message

thick bolt
#

okay then like a link to the VC I guess, just invite them to whichever one they select

slate swan
#

Like pycord nextcord ect

thick bolt
#

okay I'll watch it

#

do you think I'll be able to achieve my task after watching that

slate swan
marble rampart
#

i dont have a __init.py__ file

slate swan
marble rampart
#

i didnt import from a folder

#

or a file

#

from werkzeug.utils import secure_filenarme

slate swan
#

So it isn't local file

marble rampart
#

i have an error here

slate swan
#

It's a module??

marble rampart
#

yeah

#

ho wait i didnt saw were in discord-bots

#

mb

#

can you still help me tho

slate swan
#

Yea

marble rampart
#

?

#

do you know what to do

slate swan
#

It might be due to version of the module

#

So in the terminal of repl pip install -U Werkzeug==0.16.0

marble rampart
#

tried to change it to other version pepole said it worked for them on

#

didnt work

#

but il try pip install -U Werkzeug==0.16.0

slate swan
#

Ok good luck

marble rampart
#

nope not working

slate swan
#

Weird

marble rampart
#

thank you anyway bro

slate swan
#

I'm not familiar with the module sorry

marble rampart
#

all good

vale wing
#

Replit uses poetry, why use pip there

slate swan
#

Just me

vale wing
#

Sarth once said

waxen granite
waxen granite
slate swan
#
  • Sarth is my op
vale wing
#

But it provides better dependencies management, it allows grouping them, and if you remove main dependency it will remove all the unneeded subdependencies

vale wing
# waxen granite eh?

Same code with different objects somewhere can be refactored, in your case you could use for loop

slate swan
#
        for role in guild.roles[1:4]:
            overwrites[role] = discord.PermissionOverwrite(view_channel=True)
        await guild.create_text_channel(f"Ticket-{payload.member.display_name}", overwrites=overwrites)```
How can i disable multiple channels create
slate swan
#

You could do if the channel is in ctx.guild.channels

slate swan
# slate swan Wdym

its simple ticket system but with event on_raw_reaction_add but i dont know how can i block multiple tickets opening

slate swan
slate swan
slate swan
#

And store user id into database once ticket is open and remove when closed

#

Would be more efficient and channel then could be any name but with user id method you would need to put user id in channel name which looks tacky and unprofessional

tawdry bobcat
#

i m not able to use jishaku this error occur's

main.py:17: RuntimeWarning: coroutine 'BotBase.load_extension' was never awaited
  client.load_extension("jishaku")
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
tawdry bobcat
slate swan
#

"needs to be awaited"

quick gust
#

they told u to await it...

rare echo
#

they even sent you the docs pithink

tawdry bobcat
#

@rare echo@slate swan@quick gust

rare echo
#

very cool

quick gust
#

u have to await it is probably the simplest thing we can say

#

u can google "how to await a function"

rare echo
#

have a look at the docs, try to read and understand using the explanations and examples

tawdry grail
#

how do I get the number of people who pressed a button in a message?

slate swan
#

discord.py is not a beginner friendly Library, and awaiting is a very basic task you should know if you're making a bot

#

you'll have to keep a track of each button click indivisually in a variable

tawdry grail
#

i tried that

rare echo
tawdry grail
#

im using pycord and i made a nonlocal variable but it is saying SyntaxError: no binding for nonlocal 'countx' found

rare echo
#

do you have the code?

tawdry grail
#

yes

#

class joingame(discord.ui.View): countx = 0 @discord.ui.button(label=f"Join game", style=discord.ButtonStyle.primary) async def button_callback(self, button, interaction): nonlocal countx countx += 1 await interaction.response.send_message(f"{interaction.user} has joined this game!")

rare echo
#

remove nonlocal for it, and either setup a custom id to separate guilds or even easier, use a db

slate swan
#

why would you use nonlocal here, its a classvar

rare echo
slate swan
#

its bot a global, its a class variable

#

*not

rare echo
#

nvm didnt realize it was in the class alienpika

tawdry grail
#

thx

azure tulip
#

how to get this badge?

sick birch
azure tulip
#

How to become

slate swan
#

add a slash command to ur bot and apply for the badge

somber sky
#

I know how to add timeout like a certain time they have to click it, but how do I make it where once you click a button once you can’t click it again

ember nest
#

So I have a system with commands etc but I am wondering how I can make a command able to be used only 1 time everyday by users ?

unborn acorn
slate swan
#

!d discord.ext.commands.cooldown

unkempt canyonBOT
#

@discord.ext.commands.cooldown(rate, per, type=discord.ext.commands.BucketType.default)```
A decorator that adds a cooldown to a [`Command`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command")

A cooldown allows a command to only be used a specific amount of times in a specific time frame. These cooldowns can be based either on a per-guild, per-channel, per-user, per-role or global basis. Denoted by the third argument of `type` which must be of enum type [`BucketType`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.BucketType "discord.ext.commands.BucketType").

If a cooldown is triggered, then [`CommandOnCooldown`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CommandOnCooldown "discord.ext.commands.CommandOnCooldown") is triggered in [`on_command_error()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.discord.ext.commands.on_command_error "discord.discord.ext.commands.on_command_error") and the local error handler.

A command can only have a single cooldown.
ember nest
#

How to

#

Alright lemme see

ember nest
# unkempt canyon

But like this each user can use it 1 time per day or the whole command can be used 1 time by anyone?

somber sky
#

new to using buttons

ember nest
#

My command isn't using buttons though

somber sky
#

I’m asking about my command

sick birch
upbeat otter
slate swan
sick birch
#

Coding is great

upbeat otter
#

sometimes

sick birch
#

All my homies love coding

slate swan
slate swan
upbeat otter
#

really

#

sometimes

sick birch
#

Come on we are literally wizards who control the magic stones

#

We speak the language of the stones

slate swan
#

We write words on a screen and get 100-500k salaries

somber sky
slate swan
upbeat otter
#

That's not what they asked for lol

#

But i was going to point that out too πŸ’€

hushed galleon
#

do their views have to be persistent? looking at the initial message i was thinking shawn's asking how to disable the buttons after one of them is clicked

ember nest
#

What's the difference between
on_app_command_error1
And
on_app_command_error2

slate swan
#

none of them exist in the library

ember nest
#

Which one should I use for cooldown

slate swan
#

!d discord.app_commands.CommandTree.on_error

unkempt canyonBOT
#

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

A callback that is called when any command raises an [`AppCommandError`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.AppCommandError "discord.app_commands.AppCommandError").

The default implementation logs the exception using the library logger if the command does not have any error handlers attached to it.

To get the command that failed, [`discord.Interaction.command`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Interaction.command "discord.Interaction.command") should be used.
upbeat otter
slate swan
#

but there's no role of persistence in that lol

hushed galleon
#

ya

somber sky
#

When the buttons are clicked they expire

hushed galleon
#

in the button callback need to loop through the rest of the buttons attached to your view, disable them, and then edit the message with the newly disabled buttons

slate swan
#

!d discord.ui.Button.disabled you need to set the disable property to True and edit the view

unkempt canyonBOT
somber sky
#

thanks

azure tulip
#

why do i get this error?

somber sky
azure tulip
#

maybe, thanks

#

when I installed my light was turned off

quick gust
#

πŸ—Ώ

delicate pilot
#

How I can get the badge for my bot

quick gust
#

add a slash command to it

delicate pilot
quick gust
#

no i cannot give you slash commands

#

you will have to make them yourself

#

you can look at examples online

#

and UNDERSTAND it

delicate pilot
somber sky
#

LOL

delicate pilot
quick gust
#

@delicate pilot

#

i suggest understanding python first

#

you will keep encountering hurdles if you straight away jump to dpy

somber sky
slate swan
#

you edit the message and pass the new view, thats all

#

when you edit the component of the view, it gets updated as well

slate swan
#

Defeats the purpose so you must learn on you're own

sick birch
#

Facts

slate swan
#

badges are overrated, open source your project if you really wanna flex lol 🀺

delicate pilot
slate swan
#

!resources here's decent resources to learn python

unkempt canyonBOT
#
Resources

The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.

sick birch
#

The one good thing that came out of the badges

#

New potential developers who want to learn

slate swan
#

and some people actually trying slash commands for once

#

πŸ’€ the badge design could have been better tho, a bit of modifications in <>

slate swan
sick birch
#

Right but there are also a few people who are genuinely interested

slate swan
#

Then asking them how do you iterate through list in python and they can't answer

#

Because there's not actually devs

maiden fable
#

Wait

#

the import is from discord.ext import commands and then use commands.Bot

azure tulip
#

help

import discord
from discord.ext import commands
import os

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

bot.run(os.getenv("TOKEN"))

primal token
#

!intents

unkempt canyonBOT
#

Using intents in discord.py

Intents are a feature of Discord that tells the gateway exactly which events to send your bot. Various features of discord.py rely on having particular intents enabled, further detailed in its documentation. Since discord.py v2.0.0, it has become mandatory for developers to explicitly define the values of these intents in their code.

There are standard and privileged intents. To use privileged intents like Presences, Server Members, and Message Content, you have to first enable them in the Discord Developer Portal. In there, go to the Bot page of your application, scroll down to the Privileged Gateway Intents section, and enable the privileged intents that you need. Standard intents can be used without any changes in the developer portal.

Afterwards in your code, you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:

from discord import Intents
from discord.ext import commands

# Enable all standard intents and message content
# (prefix commands generally require message content)
intents = Intents.default()
intents.message_content = True

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

For more info about using intents, see discord.py's related guide, and for general information about them, see the Discord developer documentation on intents.

azure tulip
#

thx

fair shuttle
#

can sm1 help me lol

fair shuttle
#

no sorry i js saw

#

i dont use cogs

#

wym sorry im kinda new to this lol like i need to retype the whole thing?

slate swan
#

Wait no

#

Isn't it suppose to be a decor

fair shuttle
#

i dont think so

slate swan
#

I googled it it is

#

@kick.error
async def kick_error(error, ctx):
if isinstance(error, MissingPermissions):
await ctx.channel.send("Looks like you don't have the perm.")

fair shuttle
#

now its this lol

torn sail
#

Try ctx.author instead of ctx.member

fair shuttle
slate swan
unkempt canyonBOT
#

@discord.ext.commands.has_permissions(**perms)```
A [`check()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") that is added that checks if the member has all of the permissions necessary.

Note that this check operates on the current channel permissions, not the guild wide permissions.

The permissions passed in must be exactly like the properties shown under [`discord.Permissions`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions "discord.Permissions").

This check raises a special exception, [`MissingPermissions`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.MissingPermissions "discord.ext.commands.MissingPermissions") that is inherited from [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure").
slate swan
#

this is probably what you're after

#

to check the bot has permissions use bot_has_permissions instead

slate swan
fair shuttle
#

yeah i fixed that

#

i only have this problem now

torn sail
fair shuttle
#

like that?

sick birch
#

Lowercase c

primal token
#

and has_permissions is an attribute of commands

sick birch
#

Dot notation

slate swan
# fair shuttle like that?

It should be exactly as Matser typed it, and remember you need from discord.ext import commands if you haven't already.

sick birch
#

Dog notation lol

primal token
#

Dog notation kek

slate swan
#

🐢

fair shuttle
#

this?

#

i got it lol thank you

slate swan
fair shuttle
#

i have this big message appearing lol

sick birch
hushed galleon
#

make sure its discord.Member in your parameter typehint, with capital M

fair shuttle
primal token
#

also your string has to be an f string

hushed galleon
#

naw thats PascalCase

sick birch
fair shuttle
#

is that possible to add the user mention?

sick birch
#

!f-string

unkempt canyonBOT
#

Creating a Python string with your variables using the + operator can be difficult to write and read. F-strings (format-strings) make it easy to insert values into a string. If you put an f in front of the first quote, you can then put Python expressions between curly braces in the string.

>>> snake = "pythons"
>>> number = 21
>>> f"There are {number * 2} {snake} on the plane."
"There are 42 pythons on the plane."

Note that even when you include an expression that isn't a string, like number * 2, Python will convert it to a string for you.

sick birch
#

Notice the f before the ""

fair shuttle
#

i got it ty

#

ty for the help guys

hushed galleon
# primal token https://peps.python.org/pep-0008/#naming-conventions:~:text=CapitalizedWords%20(...

funnily enough there's one source that actually points out how dumbfoundingly confusing the definition is https://www.theserverside.com/answer/Pascal-case-vs-camel-case-Whats-the-difference

Camel case and Pascal case are similar. Both demand variables made from compound words and have the first letter of each appended word written with an uppercase letter. The difference is that Pascal case requires the first letter to be uppercase as well, while camel case does not.

fair shuttle
#

one last question is that possible to remove the 'member' in front of the tag

fair shuttle
#

alrr

hushed galleon
#

i havent seen a string representation like that before ah they manually wrote it

primal token
slate swan
#

hi

fair shuttle
#

like that @sick birch

sick birch
#

LGTM

slate swan
#

do you guys have any project recommendations for beginners?

unkempt canyonBOT
#

Kindling Projects

The Kindling projects page on Ned Batchelder's website contains a list of projects and ideas programmers can tackle to build their skills and knowledge.

fair shuttle
#

if i want the bot to tag the user when they join do i need to put the member.mention in front?

fair shuttle
#

anything wrong w that? cuz my friend dont have perm to ban and she banned sm1?

quick gust
#

show us the code of your kick command

fair shuttle
#

@quick gust

quick gust
#

u need to add the has_permissions decorator

#

!d discord.ext.commands.has_permissions

unkempt canyonBOT
#

@discord.ext.commands.has_permissions(**perms)```
A [`check()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") that is added that checks if the member has all of the permissions necessary.

Note that this check operates on the current channel permissions, not the guild wide permissions.

The permissions passed in must be exactly like the properties shown under [`discord.Permissions`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions "discord.Permissions").

This check raises a special exception, [`MissingPermissions`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.MissingPermissions "discord.ext.commands.MissingPermissions") that is inherited from [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure").
fair shuttle
quick gust
#

noo it's a decorator

fair shuttle
#

ooo

quick gust
#

@has_permissions(<perm>)

fair shuttle
#

like that sorry im kinda new to this

quick gust
#

no

#

@bot.command() is a decorator

#

it "decorates" the function

#

u put the has permissions decorator below or above that

#

without any indents

fair shuttle
#

oh

quick gust
#

also add a =True after administrator

fair shuttle
#

perfect

#

so it should look like that @quick gust

#

for ban and kick?

quick gust
#

yes

#

try it

fair shuttle
#

yeah

quick gust
#

considering you want the permission to be admin, there's more specific ones like ban_members I think

#

yeah and kick_members too

fair shuttle
#

the message didnt send tho

fading marlin
#

ctx, error, not the other way around

#

also context objects have a send shortcut coroutine

fair shuttle
#

wym/

torn sail
fair shuttle
#

OH

#

ty it worked

delicate pilot
fair shuttle
#

any1 can help lol

#

the kick one work but the ban dont

slate swan
#

@ban.error

fair shuttle
#

oh

#

im stupid lmfao

fair shuttle
slate swan
#

your command is inside another command

#

!indents please learn python indentation

unkempt canyonBOT
#

Indentation

Indentation is leading whitespace (spaces and tabs) at the beginning of a line of code. In the case of Python, they are used to determine the grouping of statements.

Spaces should be preferred over tabs. To be clear, this is in reference to the character itself, not the keys on a keyboard. Your editor/IDE should be configured to insert spaces when the TAB key is pressed. The amount of spaces should be a multiple of 4, except optionally in the case of continuation lines.

Example

def foo():
    bar = 'baz'  # indented one level
    if bar == 'baz':
        print('ham')  # indented two levels
    return bar  # indented one level

The first line is not indented. The next two lines are indented to be inside of the function definition. They will only run when the function is called. The fourth line is indented to be inside the if statement, and will only run if the if statement evaluates to True. The fifth and last line is like the 2nd and 3rd and will always run when the function is called. It effectively closes the if statement above as no more lines can be inside the if statement below that line.

Indentation is used after:
1. Compound statements (eg. if, while, for, try, with, def, class, and their counterparts)
2. Continuation lines

More Info
1. Indentation style guide
2. Tabs or Spaces?
3. Official docs on indentation

fair shuttle
earnest python
#

uhh can someone help? also yeah i didnt change repl.it to dark mode i am sorry

fair shuttle
#

why it do that?

slate swan
#

thats what you get for using replit 🀑

slate swan
#

hi

#

i tried to use argparse to do this:

#

but it seems to be blocking and slow

#

any better way to do that?

torn sail
#

!d discord.ext.commands.FlagConverter

unkempt canyonBOT
#

class discord.ext.commands.FlagConverter```
A converter that allows for a user-friendly flag syntax.

The flags are defined using [**PEP 526**](https://www.python.org/dev/peps/pep-0526) type annotations similar to the [`dataclasses`](https://docs.python.org/3/library/dataclasses.html#module-dataclasses "(in Python v3.11)") Python module. For more information on how this converter works, check the appropriate [documentation](https://discordpy.readthedocs.io/en/latest/ext/commands/commands.html#ext-commands-flag-converter).

iter(x) Returns an iterator of `(flag_name, flag_value)` pairs. This allows it to be, for example, constructed as a dict or a list of pairs. Note that aliases are not shown.

New in version 2.0.
slate swan
#

i dont think it works the same way i want

fair shuttle
slate swan
#

i need to have flags that start with -- to make it more similar to a cli

torn sail
#

there is an option to do that, lemme find the examplee

torn sail
slate swan
fair shuttle
slate swan
#

thank you

torn sail
#

πŸ‘

torn sail
slate swan
#

" " and "="

torn sail
#

oh

#

i dont think you can

slate swan
#

k then " " makes more sense

slate swan
ember nest
#

How to set

@discord.ext.commands.cooldown

Cooldown by user not for whole guild etc

slate swan
#

its for a user by default

ember nest
#

No it's for everyone for me

#

Lemme show you how I set it

#
@discord.ext.commands.cooldown(1, 600, type=discord.ext.commands.BucketType.default)
#

How do I turn it by the user?

#

@slate swan

slate swan
#

BucketType.user

somber sky
#

Command 'foapp' raised an exception: ValueError: could not find open space for item

#

what does that mean

fair shuttle
#

why its telling me that

#

i never used vscode before lol

somber sky
primal token
#

and you also need dpy iirc

slate swan
#

lmao well thats not tje issue here

fair shuttle
#

LOL

slate swan
#

the import would be valid if dpy was installed

fair shuttle
#

i never used this before

slate swan
fair shuttle
#

i got it

primal token
fair shuttle
#

js to make sure the pip install discord.py its in cmd prompt right

slate swan
#

or excessive, whatever you wanna call it

primal token
slate swan
#

given the fact that they are importing discord/commands in the code πŸ€·β€β™‚οΈ it is

primal token
#

Wasn't referring to that but alright

slate swan
#

didnt get you then, sorry

#

wasnt this thing on github blue instead of green just a few hrs ago

fading marlin
#

it's always been green πŸ€”

slate swan
#

not yesterday~

#

turns out it was just a winter theme

slate swan
#

@shy vault

#

had no idea you were here

fading marlin
sick birch
#

!pastebin your entire code, please

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.

midnight jungle
#

For some reason, the .cards command isn't doing ANYTHING.

Its not printing anything out for an exception, its not sending anything to the chat, even when i add debugging prints they don't even run even though i put them on the FIRST line.

https://paste.pythondiscord.com/idunolusev

midnight jungle
fair shuttle
#

any1 know a site for host my bot?

sick birch
midnight jungle
sick birch
midnight jungle
fair shuttle
midnight jungle
sick birch
fair shuttle
#

whats the website?

sick birch
fair shuttle
#

alrr

sick birch
#

I use AWS for hosting my websites and it's great

fair shuttle
#

perfectt

north summit
#

How can I add an embed like this because an embed requires you to have a name (where the text is always bold, which I don't want), but if i use a whitespace character to bypass name, then there is just a empty line space, how can i make it look like the pic above without any additional line spaces

fading marlin
#

No, embeds aren't required to have a title

#

they just have to have some sort of content

hushed galleon
#

it seems your image link is broken

#

get a working image link? your command is written just fine, you just need an image url that actually gives you a picture

fair shuttle
#

is there possible to add a autotrigger any1 have the link or know how

fading marlin
#

could you give a bit more context? autotrigger for what? when should it trigger?

fair shuttle
#

like when sm1 say goodnight the bot answer

fading marlin
#

!d discord.on_message this event gets dispatched every time someone sends a message

unkempt canyonBOT
#

discord.on_message(message)```
Called when a [`Message`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Message "discord.Message") is created and sent.

This requires [`Intents.messages`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.messages "discord.Intents.messages") to be enabled.

Warning

Your bot’s own messages and private messages are sent through this event. This can lead cases of β€˜recursion’ depending on how your bot was programmed. If you want the bot to not reply to itself, consider checking the user IDs. Note that [`Bot`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot "discord.ext.commands.Bot") does not have this problem.
fair shuttle
#

ty

somber sky
#

Command 'pickups' raised an exception: ValueError: Connection closed

#

what does that mean

fading marlin
#

you'll have to send more than the error

somber sky
#
@client.tree.command(description='Start a pickup')
@commands.cooldown(1, 600, commands.BucketType.user)
async def pickups(ctx, opponent: discord.Member, link: str):
 pickupseem = discord.Embed(title="Test")
 pickupseem.set_thumbnail(url=f"{ctx.guild.icon}")
 pickupseem.set_author(name=f"{client.user}", icon_url=client.user.avatar)
  
 if 'https://www.roblox.com/games/8204899140?privateServerLinkCode=' not in link:
   await ctx.response.send_message("Invalid Link", ephemeral=True)
 else:
    async with aiosqlite.connect("main.db") as db:
     async with db.cursor() as cursor:
      await cursor.execute('SELECT setpickupschannel FROM users WHERE guild = ?', (ctx.guild.id,))
    data = await cursor.fetchone()
    if not data:
      pass
    else:
      channel = client.get_channel(int(data[0]))
 async with aiosqlite.connect("main.db2") as db2:
  async with db2.cursor() as cursor:
    await cursor.execute('SELECT setcaptainrole FROM users WHERE guild = ?', (ctx.guild.id,))
    data = await cursor.fetchone()
    if not data:
      pass
    else:
      role = ctx.guild.get_role(int(data[0]))
    if 'https://www.roblox.com/games/8204899140?privateServerLinkCode=' in link:
     if role in ctx.user.roles:
      await ctx.response.send_message("Succesfully Sent Pickup.", ephemeral=True)
      await channel.send(embed=pickupseem)
      await channel.send(f"@here")```
fading marlin
#

why are you opening and closing 2 connections in the same command?

#

also, consider doing ```py
if data:
channel = client.get_channel(...)

and remove the `else`. It makes your code more readable
#

anyway, for the actual error, you're calling cursor.fetchone outside of the context manager

somber sky
#

whaat does thaat mean

fair shuttle
#

@sick birch wich one i need to select

sick birch
azure tulip
#

what's wrong here?

fading marlin
# somber sky whaat does thaat mean
  • calling aiosqlite.connect(...) creates a new connection. You're doing that twice in your command... why?
  • your if statements aren't really readable
if not data:
    pass
else:
    ...

is exactly the same as doing

if data:
    ...

consider doing the latter instead

  • with statements are also called context managers
#  outside the context manager
with open(...) as fp:
    ...  # inside the context manager
#  outside the context manager

when you exit connect's context manager, you're closing the connection between your database. Once your connection is closed, you cannot interact with the database anymore. cursor.fetchone requires you to have an open connection, but you're calling it outside the context manager

fading marlin
unkempt canyonBOT
#

Using intents in discord.py

Intents are a feature of Discord that tells the gateway exactly which events to send your bot. Various features of discord.py rely on having particular intents enabled, further detailed in its documentation. Since discord.py v2.0.0, it has become mandatory for developers to explicitly define the values of these intents in their code.

There are standard and privileged intents. To use privileged intents like Presences, Server Members, and Message Content, you have to first enable them in the Discord Developer Portal. In there, go to the Bot page of your application, scroll down to the Privileged Gateway Intents section, and enable the privileged intents that you need. Standard intents can be used without any changes in the developer portal.

Afterwards in your code, you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:

from discord import Intents
from discord.ext import commands

# Enable all standard intents and message content
# (prefix commands generally require message content)
intents = Intents.default()
intents.message_content = True

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

For more info about using intents, see discord.py's related guide, and for general information about them, see the Discord developer documentation on intents.

azure tulip
#
import discord
from discord import Intents
from discord.ext import commands

intents = Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix="!", intents=intents)



@bot.event
async def on_ready():
    print("Bot started")
    await Bot.change_presence(status=discord.Status.idle, activity=discord.game(""))


bot.run('TOKEN')
#

what he doesn't like about bot.run('TOKEN')

fading marlin
#

that you're not passing an actual token

#

don't change presences in on_ready either

#

commands.Bot has an activity and status kwarg

azure tulip
#

ok

fickle sky
#

24/7

fair shuttle
fading marlin
sick birch
fair shuttle
#

why

fading marlin
#

would you give me the token of your bot? probably not. Same thing applies

sick birch
# fair shuttle why

I would not be placing some random person's supposed host over an industry standard like AWS

fair shuttle
#

oh okok

rare echo
#

im posting this as a new method of showing people a locally hosted bot

north summit
#

is there way to find a role with only the first half of the role name provided?
ex: find the role named "pic perms" with only the "pic" parameter

torn sail
sick birch
#

Where roles is a Sequence[discord.Role]

azure tulip
#

how to get this badge?
I made a bot that has a command through a slash

sick birch
#

If it's not there it can take a while

#

If it's still not there then discord probably put more restrictions on it

fair shuttle
#

why when i put these commands other commands dont work

rare echo
#

you need uhh, bot.process_commands i think its called

#

yes , await bot.process_commands(message)

sick birch
#

It lets you:

  1. Have more than one on_message (events don't let you do this)
  2. Not need to use bot.process_commands
somber sky
# sick birch ```py if GMRole in i.user.roles or HCRole in i.user.roles: ... ```

I'm still trying to fix this. This is my current code. It's still not working.

@client.tree.command(name='promote', description='Promote a player.')
@app_commands.choices(position=[
    app_commands.Choice(name="General Manager", value="General Manager"),
    app_commands.Choice(name="Head Coach", value="Head Coach"),
    ])
async def promote(i: discord.Interaction, user:discord.Member, position: app_commands.Choice[str]):
    GMRole = discord.utils.get(i.guild.roles, name="General Manager")
    HCRole = discord.utils.get(i.guild.roles, name="Head Coach")
    FORole = discord.utils.get(i.guild.roles, name="Franchise Owner")
    teams = discord.utils.find(lambda r: r.name in nflRoleListNames, i.user.roles)
    teams2 = discord.utils.find(lambda r: r.name in nflRoleListNames, user.roles)
    if FORole not in i.user.roles:
     await i.response.send_message("You are not a Franchise Owner.", ephemeral=True)
     return
    if teams not in user.roles:
     await i.response.send_message(f"User is not on your team.")
     return
    if GMRole in i.user.roles or HCRole in i.user.roles:
      await i.response.send_message("Someone is already coach")
      return
    else:
        if FORole in i.user.roles:
          if any(role.name in nflRoleListNames for role in user.roles):
           if (position.value == 'General Manager'):
             await user.add_roles(GMRole)
             await i.response.send_message(f"Promoted user to General Manager")
           if (position.value == 'Head Coach'):
             await user.add_roles(HCRole)
             await i.response.send_message("Promoted user to Head Coach")```

If the team alreaady has GMRole or HCRole, then you cant run the command thats whats supposed to happen but it doesnt work
fair shuttle
#

one last question if i want to add a channel in my welcome message its like that?

#

i added the id of the channel w #

rare echo
#

oh nvm, that should work to just mention it

fair shuttle
#

exactly what i did

somber sky
#

idk how to makae it where if SOMEONE in teams has

#

i only know if teams in user

somber imp
somber sky
#

exactly

somber sky
#

0 clue

fair shuttle
#

if i want to add a emoji to a message how i can do that?

somber sky
#

a custom emoji ^

fair shuttle
#

alr

somber sky
#

@fair shuttle put the emoji and put \ before it

#

then send

#

it gives u the whole thing

fair shuttle
#

like that

somber sky
#

yea

fair shuttle
#

hmmm

somber sky
#

send me the emoji rq i wanna seee something

#

if you haave nitro

fair shuttle
somber sky
#

alr i was just seeing if u haad the right id

#

idk then

somber sky
#

the bot has to be in the server the emoji is in i think

fair shuttle
#

oh

somber sky
#

yeaa so just upload the emoji in ur seerver and try

fair shuttle
#

yeah

loud junco
#

a bit off topic but what is going on

#

my bot is in 100 servers and i verified myself now what

tawdry grail
#

is it possible to add SelectOptions to a select menu in pycord using for loop?

tawdry grail
#

how?

somber sky
torn sail
upbeat otter
# tawdry grail how?
par = {
      "option_one" : 
                  {"label": "Red", 
                             "value" : "red"}, 
      "option_two": 
                  {"label": "Blue",
                             "value": "blue"}}

for param in par:
  self.add_item(SelectOption(label = param["label"], value = param["value"])) #whatever the method is to add select options if not add_item

you can use any iterable you desire

somber sky
tawdry grail
# upbeat otter ```py par = { "option_one" : {"label": "Red", ...

`class Shoot(discord.ui.View):
players = joingame.players

@discord.ui.select(
    placeholder="Choose a person to shoot!",
    min_values=1,
    max_values=1,
    options=[]
)
async def select_callback(self, select, interaction):
    await interaction.response.send_message(f"You have shooted them")`

my current code is like this. it will give an error when i try to put the for loop anywhere in it

upbeat otter
#

what error

shrewd fjord
#

sup

shrewd fjord
tawdry grail
#
class Shoot(discord.ui.View):
    players = joingame.players

    @discord.ui.select(
        placeholder="Choose a person to shoot!",
        min_values=1,
        max_values=1,
        options=[]

        for player in players:
            self.add_item(SelectOption(label = player, value = "shoot this player."))
    )
    async def select_callback(self, select, interaction):
        await interaction.response.send_message(f"You have shooted them")```
this is code:

it will give `Syntax Error: invalid syntax`
shrewd fjord
#

invalid syntax

#

we cant hellp with syntax error

#

fix yourself

somber imp
upbeat otter
#

use the __init__ method

#
def __init__(self) -> None:
  for ...
tawdry grail
#

ok

somber sky
#

thanks bro it worked

somber imp
somber imp
tawdry grail
somber sky
# somber imp Haha you gotta checks docs know some python tricks to pull these things off

yo one question, gonna be a little confusing.

async def promote(i: discord.Interaction, user:discord.Member, position: app_commands.Choice[str]):
    GMRole = discord.utils.get(i.guild.roles, name="General Manager")
    HCRole = discord.utils.get(i.guild.roles, name="Head Coach")
    FORole = discord.utils.get(i.guild.roles, name="Franchise Owner")
    teams = discord.utils.find(lambda r: r.name in nflRoleListNames, i.user.roles)
    teams2 = discord.utils.find(lambda r: r.name in nflRoleListNames, user.roles)
    if FORole not in i.user.roles:
     await i.response.send_message("You are not a Franchise Owner.", ephemeral=True)
     return
    if teams not in user.roles:
     await i.response.send_message(f"User is not on your team.")
     return
    if GMRole in [member_role for team_member in teams2.members for member_role in team_member.roles]:
     await i.response.send_message("Someone is already General Manager")
     return
    if HCRole in [member_role for team_member in teams2.members for member_role in team_member.roles]:
     await i.response.send_message("Someone is already Head Coach")
     return
    else:
        if FORole in i.user.roles:
          if any(role.name in nflRoleListNames for role in user.roles):
           if (position.value == 'General Manager'):
             await user.add_roles(GMRole)
             await i.response.send_message(f"Promoted user to General Manager")
           if (position.value == 'Head Coach'):
             await user.add_roles(HCRole)
             await i.response.send_message("Promoted user to Head Coach")```

There are 2 coach roles. It's supposed to be, all teams can have 1 GMRole and 1 HCRole. When I promote someon to GMRole, I cant to HCRole it says someone is already general manager, but it should only say that if i try to promote someone to GMRole when there alreaady is one. How do i fix this?
#

i explained it awfully but

#

hopefully you understand if u dont ill try to explain better

#

Better explanation.

Every team has a maximum of 1 GMRole and 1 HCRole. If the team alreaady has a GMRole and you try to run the command. It'll say Someone is already general manager. Which is good. But when I try to promote someone to HCRole, It'll say the same thing. (someone is already general manager) It shouldn't do that because HCRole has its own if statement.

bright wedge
somber sky
# bright wedge then define somehow the user who can do the promotes!. If I understand correctly...
@client.tree.command(name='promote', description='Promote a player.')
@app_commands.choices(position=[
    app_commands.Choice(name="General Manager", value="General Manager"),
    app_commands.Choice(name="Head Coach", value="Head Coach"),
    ])
async def promote(i: discord.Interaction, user:discord.Member, position: app_commands.Choice[str]):
    GMRole = discord.utils.get(i.guild.roles, name="General Manager")
    HCRole = discord.utils.get(i.guild.roles, name="Head Coach")
    FORole = discord.utils.get(i.guild.roles, name="Franchise Owner")
    teams = discord.utils.find(lambda r: r.name in nflRoleListNames, i.user.roles)
    teams2 = discord.utils.find(lambda r: r.name in nflRoleListNames, user.roles)
    if FORole not in i.user.roles:
     await i.response.send_message("You are not a Franchise Owner.", ephemeral=True)
     return
    if teams not in user.roles:
     await i.response.send_message(f"User is not on your team.")
     return
    else:
        if FORole in i.user.roles:
          if any(role.name in nflRoleListNames for role in user.roles):
           if GMRole in [member_role for team_member in teams2.members for member_role in team_member.roles]:
             await i.response.send_message(f"Someone is already General Manager", ephemeral=True)
             return
           if (position.value == 'General Manager'):
             await user.add_roles(GMRole)
             await i.response.send_message(f"Promoted user to General Manager")
             return
          else:
           if HCRole in [member_role for team_member in teams2.members for member_role in team_member.roles]:
             await i.response.send_message(f"Someone is already Head Coach", ephemeral=True) 
             return
        else:
           if (position.value == 'Head Coach'):
             await user.add_roles(HCRole)
             await i.response.send_message("Promoted user to Head Coach")
             return```
#

everytime I add HCRole, it says someeonmee is aalready geeneral manager

#

idk why though, i returneed it, I did else:

#

idk why when i do HCRole it gives me the GMRole message

slate swan
#

anyone know where to find a list where stuff like on_member_join and on_member_remove would be

somber imp
somber sky
#

i fixed it alreaady its fine

somber imp
somber imp
somber sky
#

what does ProgrammingError: Cannot operate on a closed cursor. mean

#
    async with aiosqlite.connect("main.db") as db:
      async with db.cursor() as cursor:
        await cursor.execute('SELECT settransactionschannel FROM users WHERE guild = ?', (i.guild.id,))
      data = await cursor.fetchone()
      if not data:
        pass
      else:
        channel = client.get_channel(int(data[0]))
        await channel.send_message(embed=promoteem)
        return```
naive briar
#

Just move it 1 indent up

ocean dragon
#

how do Cogs work? If I want to use a similar way to define methods in different folders and combine them into one class

#

do they just inherit each class until everything is inherited

pliant gulch
#

Are you asking how to use cogs? Or how does the internals work

slate swan
pliant gulch
#

Cogs act like a module in a way. The Cog class that you inherit uses a meta-class to scan all methods before construction to "bind" commands and listeners to the Cog class. Afterwards using load_extension does an importlib lookup where it looks for the module using the path, E.g foo.bar then looks for a TOP-level method setup that just binds the Bot instance to the cog via injecting commands & listeners that were binded to the Cog earlier

#

!e ```py
from typing import Any, Callable, Self

class FooMeta(type):
commands: dict[str, Callable]

def __new__(cls, name: str, bases: tuple[type, ...], namespace: dict[str, Any]) -> Self:
    commands: dict[str, Callable] = {}

    for key, value in namespace.items():
        if callable(value):
            commands[key] = value
            
    namespace["__commands__"] = commands
    return super().__new__(cls, name, bases, namespace)

class Foo(metaclass=FooMeta):
commands: dict[str, Callable]

def __init__(self) -> None:
    self.commands = self.__class__.__commands__

class Cog(Foo):
def foo(self) -> None:
print("bar")

cog = Cog()
print(cog.commands)

unkempt canyonBOT
#

@pliant gulch :white_check_mark: Your 3.11 eval job has completed with return code 0.

{'foo': <function Cog.foo at 0x7ff1105cc4a0>}
steel mango
#

im following a tutorial to make a discord bot and im getting the error "client has no attribute command" for @opaque fiber

naive briar
#

Don't follow tutorials

#

Most of them won't teach you anything

#

And only discord.ext.commands.Bot has command decorator

#

!d discord.ext.commands.Bot.command

unkempt canyonBOT
#

@command(*args, **kwargs)```
A shortcut decorator that invokes [`command()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.command "discord.ext.commands.command") and adds it to the internal command list via [`add_command()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.GroupMixin.add_command "discord.ext.commands.GroupMixin.add_command").
shell wing
#
@bot.command()
async def lock(ctx, channel: discord.TextChannel = None):
    overwrite = ctx.channel.overwrites_for(ctx.guild.default_role)
    overwrite.send_messages = False
    await ctx.channel.set_permissions(ctx.guild.default_role,
                                      overwrite=overwrite)
    await ctx.send('Channel locked.')
  ``` how can i make it lock a particular channel for a particular role
naive briar
#

Pass the role object into the set_permissions method

#

!d discord.TextChannel.set_permissions

unkempt canyonBOT
#

await set_permissions(target, *, overwrite=see - below, reason=None, **permissions)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Sets the channel specific permission overwrites for a target in the channel.

The `target` parameter should either be a [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member "discord.Member") or a [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role "discord.Role") that belongs to guild.

The `overwrite` parameter, if given, must either be `None` or [`PermissionOverwrite`](https://discordpy.readthedocs.io/en/latest/api.html#discord.PermissionOverwrite "discord.PermissionOverwrite"). For convenience, you can pass in keyword arguments denoting [`Permissions`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions "discord.Permissions") attributes. If this is done, then you cannot mix the keyword arguments with the `overwrite` parameter.

If the `overwrite` parameter is `None`, then the permission overwrites are deleted.

You must have [`manage_roles`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_roles "discord.Permissions.manage_roles") to do this...
steel mango
shell wing
#

cause i tried and it didnt work

slate swan
#

you ask for a channel arg in the command and yet you're editing ctx.channel, why?

naive briar
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.

shell wing
# naive briar Exact same but with other role that's not `ctx.guild.default_role`
@client.command()
async def lock(ctx, channel : discord.TextChannel=None):
    overwrite = ctx.channel.overwrites_for(ctx.guild.get_role(934391119041687593))
    overwrite.send_messages = False
    channel = client.get_channel(936641493534404638)
    await ctx.channel.set_permissions(                    overwrite=overwrite)
    print("heyo")
    await ctx.send('Channel locked.')  
``` like this ?
naive briar
#

Edit the message with the edited view

slate swan
#

edit_message(content="your stuff", view=self)

#

edit_message has kwargs only

#

use a proper IDE and type checker to avoid mistakes like this

wheat gyro
#

Hi o7 new here so sorry for the absolute beginner questions, I will have a few over the next few weeks probably πŸ˜„

#

Is there a website which will help create a slash command modal form in python?

#

I used an online site to create a bot previously and it was in java but I want to host my own bot and write it in python instead and I have search several modal results but cant find anything and I'm struggling to understand it

#

I need a modal form to popup when a user types /rally

slate swan
#

!d discord.ui.Modal