#discord-bots

1 messages Β· Page 1144 of 1

lilac mica
#

What is that

paper sluice
grim oar
#

Zeffo what was that

vale wing
lilac mica
grim oar
#

Very based

lilac mica
#

Ok ill install it

paper sluice
lilac mica
#

oh

lilac mica
paper sluice
#

bro stop it, we all know

slate swan
vocal plover
#

motherfucker isnt a racial slur anyways

paper sluice
lilac mica
grim oar
lilac mica
#

Neo vim looks hard to learn

daring olive
#

let's bring it back to discord bots

vale wing
#

They like birch so much

vale wing
vocal plover
#

this server jfc

slate swan
#

.topic

lament depotBOT
#
**What unique features does your bot contain, if any?**

Suggest more topics here!

lilac mica
#

Im making a multi purpose discord bot

slate swan
paper sluice
vale wing
slate swan
#

sorry ryuga πŸ˜” i wont do it again

lilac mica
vocal snow
#

could you send the code and error

vale wing
#

I have a bunch of word filter algs

slate swan
paper sluice
vale wing
#

We are talking so nice about discord bots

vocal plover
#

Bad word filters are a pet hate of mine, because they're rarely ever implemented correctly, and even when they are they're usually used incorrectly anyway

paper sluice
#

same

grim oar
#

then give a robust alternative ig?

lilac mica
#

Guys i've heard this reg ex is good for filtering bad words?

paper sluice
#

its mostly any(word in message for word in bad_words)
which is not the way to check

lilac mica
#

What is it?

cold sonnet
vale wing
lilac mica
#

Tutorial?

cold sonnet
#

$hit

vale wing
#

There are a bunch of them including python docs

cold sonnet
#

these are all bad words you have to think of

#

when making a filter

grim oar
#

And put them in the woodpile for maximum efficiency

vale wing
#

@cold sonnet you should try my word filter 😏

cold sonnet
#

ßitch

vocal plover
#

The way Discord's new bad word filter is implemented is decent, it is based off whole words with the possibility to add wildcards

#

it's not perfect but for Discord's scale it's not a half bad solution

paper sluice
lilac mica
#

Tutorial?

paper sluice
vale wing
#

No way it got 4 stars 😳

lilac mica
lilac mica
#

Does it delete woodpile words

vale wing
#

Thanks

vocal snow
#

what are woodpile words

vale wing
#

Tho I mostly rely on character whitelist

lilac mica
#

Like you know n*ga in the woodpile f*g in the woodpile

#

Anything like that

vocal snow
#

wtf

vale wing
#

The what

lilac mica
#

Also no htat is not a slur i censored it

daring olive
#

!mute 995719300344205342 I said to move on to discord bots

unkempt canyonBOT
#

:incoming_envelope: :ok_hand: applied mute to @lilac mica until <t:1657474685:f> (59 minutes and 59 seconds).

vocal plover
#

We are on Discord bots.

#

He was talking about Discord bots

vale wing
#

Yeah

#

About implementing word filter

paper sluice
grim oar
#

yep

daring olive
#

let me discuss something with them in modmail

slate swan
vocal plover
paper sluice
#

imma go have dinner πŸ‘‹

slate swan
grim oar
#

doxxxxing

maiden fable
tough lance
#

πŸ’€

vocal plover
#

but yeah I went though every unicode char by hand lol

maiden fable
#

Nice, at least now I know I am not the only person who has a lot of free time

slate swan
#

inhumane

vocal plover
#

redbull and snacks

#

too much of both

maiden fable
#

Hm, understandable

slate swan
#

oh well energy drinks πŸ˜” can relate

maiden fable
#

I drank one day before yesterday and pretty much was awake all night

grim oar
#

Too much free time

vocal plover
#

I've had 4 redbulls in my life and half of them were for that list lol

tawdry perch
paper sluice
#

drinks/caffine doesn't seem to affect me, like i have never felt like i dont want to sleep after drinking coffee

slate swan
#

I think I should stop drinking everyday now

#

πŸ˜”

tawdry perch
slate swan
#

godly

#

πŸ‘€

#

i have a plan to not sleep and do all my homework today

grim oar
#

Good boy

#

Make parents proud

slate swan
shrewd apex
slate swan
#

do asher's reactions look fake-like to me or what πŸ˜”

slate swan
slate swan
shrewd apex
#

...

#

it was genuine

slate swan
#

same thing

grim oar
#

!ot

unkempt canyonBOT
slate swan
#

😴

#

πŸ₯±

paper sluice
#

sleep, otherwise you will miss the bus to school

grim oar
#

I drive tuktuk, I take him to school.

slate swan
#

if i slept i would have get 0

#

projects / ppt submittion last date tmrw

paper sluice
#

ouf

slate swan
#

πŸ’€

shrewd apex
#

lmfao

grim oar
#

Is the ppt on β€œdid wizard hit the mommy” perhaps

shrewd apex
#

English class 12πŸ’€

grim oar
#

It was I who abused aunt Jennifer

tough lance
#

!ot

unkempt canyonBOT
tough lance
#

Heh

shrewd apex
#

f coz of u another dumb poem ;-;

tough lance
#

I understood every single word

slate swan
#

😱

#

pro

shrewd apex
#

lip readerπŸ‘€

grim oar
#

lip kisser

slate swan
#

clipped

grim oar
#

Now I can't even kiss on lips bro

slate swan
#

!ot or next ping to mods

unkempt canyonBOT
grim oar
#

Install linux now

#

Which one

slate swan
#

goto ot or ill call mods they will give u mute

grim oar
#

Another cool hecker boii, desktop environment or window manager

slate swan
#

rly?

grim oar
#

Let's move to ot, he being a dick

slate swan
#

😑

#

i got 3 months ban

#

delete it pls

#

<@&831776746206265384> .... ot

daring olive
#

hello

slate swan
#

hi

#

πŸ˜‡

#

πŸ˜„

grim oar
#

What a dick

slate swan
#

i dont want ban so calm down

daring olive
#

I'm here

slate swan
#

!ot

unkempt canyonBOT
daring olive
#

everyone please abide by our #rules and #code-of-conduct
that means staying on topic, not insulting one another by calling them dicks, etc.

slate swan
#

πŸ˜”

#

or just !shh the channel easy

daring olive
#

last warning for everyone

slate swan
#

danny is a doctor cuz

daring olive
#

I saw dpy has tons of regular updates since they restarted development

slate swan
#

funny

slate swan
vocal plover
#

I mean its a fair point

#

dpy was made because danny needed a discord lib, I'd assume

grim oar
#

There tree crap sucks balls

slate swan
#

wheel was invented y a human nit a cave

daring olive
vocal plover
#

either get or fetch the channel object by ID and then send to it

slate swan
vocal plover
#

Client.get|fetch_channel

slate swan
#

make requests to the api easyyy

vocal plover
#

make a raw request then

#

sucks

slate swan
#

then what do you expect

vocal plover
#

"I want a car but I don't want it to have wheels"

slate swan
#

everything on web works using requests

vocal snow
grim oar
vocal plover
#

gRPC is now sad

slate swan
#

same thing ggghhfjj

#

hi

#

hello

grim oar
shrewd apex
slate swan
#

loool nova

slate swan
#

I uh, offtopic pretty fast

#

see

#

it was a shitpost

#

that i posted

#

and new convo begins

paper sluice
#

!ot dont make me do it πŸ’€

vocal plover
#

I swear this chat becomes less useful every time I look

grim oar
#

L

shrewd apex
#

sparky laying baits

vocal plover
vocal snow
#

In which cases would Guild.voice_client not be an instance of VoiceClient?

slate swan
#

amen.

paper sluice
grim oar
#

If you want useful crap then go to discordpy or any specific help server, this place ain't it

slate swan
#

ot-3-discord-bots

slate swan
vocal snow
#

I care because my linter won't shut up

slate swan
#

abuse it physically

grim oar
#

noqa

vocal plover
#

you're using pycord I assume?

vocal snow
#

No, dpy 2.0

slate swan
#

ew

grim oar
paper sluice
#

!d discord.Guild.voice_client

slate swan
#

imagine using pycord

grim oar
#

Use it

unkempt canyonBOT
#

property voice_client```
Returns the [`VoiceProtocol`](https://discordpy.readthedocs.io/en/latest/api.html#discord.VoiceProtocol "discord.VoiceProtocol") associated with this guild, if any.
vocal plover
#

ah, a proto

slate swan
paper sluice
#

ya its VoiceProtocol not VoiceClient

slate swan
#

ew

grim oar
#

Misleading name

paper sluice
#

its dpy, its expected

vocal plover
# slate swan ** **

I don't wanna sound harsh but if you're going to contribute literal empty messages instead of anything remotely on-topic please just don't.

vocal snow
#

When I want to use a method of VoiceClient I have to assert/isinstance prior otherwise my linter starts throwing gang signs. Any suggestions?

grim oar
#

noqa it ffs

#

freaking loser

vocal plover
#

can you typehint it as a VoiceProtocol and then use the proto methods?

grim oar
#

cast it yes

#

!d typing.cast

unkempt canyonBOT
#

typing.cast(typ, val)```
Cast a value to a type.

This returns the value unchanged. To the type checker this signals that the return value has the designated type, but at runtime we intentionally don’t check anything (we want this to be as fast as possible).
vocal plover
#

christ can we actually stay on the bloody topic not just send meaningless spam

slate swan
daring olive
#

!mute 431677941722906625 incident_investigating

unkempt canyonBOT
#

:incoming_envelope: :ok_hand: applied mute to @grim oar until <t:1657478900:f> (59 minutes and 59 seconds).

slate swan
#

poor nova

vocal snow
vocal plover
#

wrong id i assume?

vocal snow
vocal plover
#

you do uh

slate swan
daring olive
#

giving help with phrases like ffs and loser aren't in line with our code of conduct

#

please stop spamming.

vocal plover
#
my_thing = typing.cast(VoiceClient, extisting_object)

and that signals to the type checker that my_thing is a VoiceClient no matter what type it thinks it is

vocal snow
#

Ah i see

#

Ok that's useful, ty vco and @grim oar

vocal plover
#

*clearly to us, not necessarily an outside view of the convo

daring olive
#

public community means public moderation policy, so no, those comments won't fly here

wary shadow
slate swan
#

no

slate swan
#

they do

#

being a mod/admin in such a big community

vocal plover
#

It's rewarding /shrug

#

no.

slate swan
#

can you guys just stop shitposting at this point

wary shadow
#

Generally helping guide and maintain a community that, for the most part, is incredibly helpful to each other.

slate swan
#

im not sleeping so

shrewd apex
slate swan
#

here we go

slate swan
cold sonnet
slate swan
torn sail
slate swan
#

its 27

hardy yoke
#

!ot

unkempt canyonBOT
#

The rules and guidelines that apply to this community can be found on our rules page. We expect all members of the community to have read and understood these.

slate swan
#

!e
print("True"[-1],"g"*2)

unkempt canyonBOT
#

@slate swan :white_check_mark: Your eval job has completed with return code 0.

e gg
#

4. Use English to the best of your ability. Be polite if someone speaks English imperfectly.

vast gale
#

there's a channel for bot commands lol

#

while the name of the channel being discord-bots may confuse you into thinking it is a command channel, this is not #bot-commands

daring olive
#

!tban 953394680073179207 1m repeat offender and history of not following our rules on 2 accounts.

unkempt canyonBOT
#

:incoming_envelope: :ok_hand: applied ban to @white raft until <t:1660155104:f> (30 days and 23 hours).

fresh notch
#
@bot.event
async def on_message_delete(message, ctx):
    embed = discord.Embed(title="Message Deleted", description=f"Message by {message.author.name} was deleted", color=0x00ff00)
    await ctx.send(embed=embed)
TypeError: Client.event() missing 1 required positional argument: 'coro'
#

i dont understand whats wrong

cold sonnet
#

remove ctx

#

use await message.channel.send

fresh notch
#
@bot.event
async def on_message_delete(message):
    embed = discord.Embed(title="Message Deleted", description=f"Message by {message.author.name} was deleted", color=0x00ff00)
    await message.channel.send(embed=embed)
cold sonnet
#

yes

fresh notch
#

gives the same error

wary shadow
#

Make sure you save and relaunch it.

fresh notch
#

bot = commands.Bot(command_prefix=';', intents=intents)

vocal snow
#

Looks like you forgot to instantiate Client

cold sonnet
#

do you use @bot.event with () somewhere in your code

fresh notch
#

yes

cold sonnet
#

remove the () from there

#

you don't call @bot.event

fresh notch
#
import discord
from discord.ext import commands

intents = discord.Intents.default()
intents.members = True
intents.messages = True
bot = commands.Bot(command_prefix=';', intents=intents)

@bot.event
async def on_ready():
        print('Up and running:', bot.user.name)

@bot.event
async def on_message_delete(message):
    embed = discord.Embed(title="Message Deleted", description=f"Message by {message.author.name} was deleted", color=0x00ff00)
    await message.channel.send(embed=embed)

what exactly do i change

cold sonnet
#

seems good

#

save the code, kill the terminal, rerun the code

fresh notch
#

gives the same erorr

#

even when i run it on cmd

cold sonnet
#

do you have another event

fresh notch
#

no below this is just commands

cold sonnet
#

that's weird

fresh notch
#

alr i removed the entire thing and pasted it again

#

works now

#

thanks

cold sonnet
#

you probably didn't save...

#

doesn't matter, good job

hardy yoke
#

what library is this

cold sonnet
#

definitely not

flat solstice
#

does anyone have an 'empty'/invisible' ascii character that I can put in my embed field value to make the code think somehtings there when there isn't somehting there

slate swan
#

U200b

#

anyone know fix?

#

"** **"

#

im active asf for asking questions here istg

swift pumice
#

i still couldnt find a solution(and with the hardcoding i couldnt figure it out)

cold sonnet
#

even though you're not in a class

slate swan
#

oh wait i did

cold sonnet
#

you don't use self outside of classes

slate swan
#

should i just remove that?

cold sonnet
#

yes

flat solstice
# slate swan U200b

is there anyhting I need to wrap this in? Tried doing \U200b but got a unicode errorpy SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 0-5: truncated \UXXXXXXXX escape

slate swan
#

like this

cold sonnet
#

β€Ž

flat solstice
#

yep

slate swan
#

** **

#

use this inside string

flat solstice
#

okay thanks

slate swan
#

called it

lilac mica
#

Okimii

cold sonnet
#

how would it be nextcord

#

@discord.slash_command()

slate swan
hardy yoke
#

might be worth asking in their server not sure if pycord is commonly used here

slate swan
flat solstice
slate swan
# cold sonnet yes

thanks. also how would i go about making this create a private channel so only mods can see it?

hardy yoke
#

it's linked on their docs

cold sonnet
unkempt canyonBOT
#

await create_text_channel(name, *, reason=None, category=None, news=False, position=..., topic=..., slowmode_delay=..., nsfw=..., overwrites=..., default_auto_archive_duration=...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Creates a [`TextChannel`](https://discordpy.readthedocs.io/en/latest/api.html#discord.TextChannel "discord.TextChannel") for the guild.

Note that you need the [`manage_channels`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_channels "discord.Permissions.manage_channels") permission to create the channel.

The `overwrites` parameter can be used to create a β€˜secret’ channel upon creation. This parameter expects a [`dict`](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.10)") of overwrites with the target (either 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")) as the key and a [`PermissionOverwrite`](https://discordpy.readthedocs.io/en/latest/api.html#discord.PermissionOverwrite "discord.PermissionOverwrite") as the value.

Note

Creating a channel of a specified position will not update the position of other channels to follow suit. A follow-up call to [`edit()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.TextChannel.edit "discord.TextChannel.edit") will be required to update the position of the channel in the channel list...
cold sonnet
#

you see the overwrites parameter?

slate swan
#

youre welcome

cold sonnet
#

the overwrites parameter takes a dict, with a role as key and permissions as name

#

you might wanna have something like

flat solstice
cold sonnet
#

wait I have to go see some examples

slate swan
slate swan
cold sonnet
cold sonnet
flat solstice
ashen notch
#

No reason to cop an attitude

cold sonnet
#

the key of the dict is the role, the name is a discord.PermissionsOverwrite instance

#

or a list of discord.PermissionsOverwrite instances

slate swan
#

they are like a pop up menu allowing to input something then submit it

slate swan
slate swan
flat solstice
# slate swan code pls

got it sorted πŸ˜„ altho I think I abused TheMethGuy's generosity and integrity. For a ida of what was being a problempy embed.add_field(name=article.label, value=article.description if article.description else " ",) # Invisable char in the string kept telling me the field value was required, my fix thanks to TheMethGuy was py embed.add_field(name=article.label, value=article.description if article.description else "\u200b",) # Uising unicode emoji instead of invisable char

slate swan
#

πŸ‘

cold sonnet
#

I assume it's meant to be ctx.author

#

you also have two unnecessary wait_fors after await msg.add_reaction()

#

it's also str(reaction.emoji), not str(reaction) in your check

cold sonnet
#

!d discord.ext.commands.Bot.wait_for

unkempt canyonBOT
#

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

Waits for a WebSocket event to be dispatched.

This could be used to wait for a user to reply to a message, or to react to a message, or to edit a message in a self-contained way.

The `timeout` parameter is passed onto [`asyncio.wait_for()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.wait_for "(in Python v3.10)"). By default, it does not timeout. Note that this does propagate the [`asyncio.TimeoutError`](https://docs.python.org/3/library/asyncio-exceptions.html#asyncio.TimeoutError "(in Python v3.10)") for you in case of timeout and is provided for ease of use.

In case the event returns multiple arguments, a [`tuple`](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.10)") containing those arguments is returned instead. Please check the [documentation](https://discordpy.readthedocs.io/en/latest/api.html#discord-api-events) for a list of events and their parameters.

This function returns the **first event that meets the requirements**...
cold sonnet
#

might wanna take a look at the examples here

slate swan
#

and also how would i go about once the bot makes the channel it gives a closing option by pressing button? (if it doesnt mean using a db)

#

will do

faint monolith
lilac mica
slate swan
#

kinda like what the ticket bot has?

#

if i made sense there

#

how to check if a channel has nsfw on

#

nvm

#

hi

slate swan
#

!d discord.TextChannel.nsfw

unkempt canyonBOT
slate swan
#

how do i get the whole phrase sent by user in bot command

#

and store it

slate swan
#

how do i make my bot online 24/7?

#

!d discord.ext.commands.Context.message

unkempt canyonBOT
#

The message that triggered the command being executed.

Note

In the case of an interaction based context, this message is β€œsynthetic” and does not actually exist. Therefore, the ID on it is invalid similar to ephemeral messages.

slate swan
#

Oohhh

slate swan
#

i can host on the bot somehow and somewhere online or something?

sick birch
#

You will still be running the file 24/7, but on someone else's computer

slate swan
#

how much vps?

sick birch
#

Depends on where you get it from

slate swan
#

germany

sick birch
#

I mean, from who you buy the VPS from

#

E.g GCP, AWS, MS Azure, etc

slate swan
#

ah okay

austere herald
#

Err my bot is refusing to respond to commands

slate swan
#

is there anything better and faster around the bot 24/7 online?

austere herald
#

I have no on_message event override in my subclass, message content intent is enabled and my command cogs have loaded

#

What's up now?

sick birch
austere herald
#

When I do override on_message to print and THEN process commands it prints out the message just fine

#

But the commands aren't processing

sick birch
slate swan
#

a hoster or something where i can install the bot or something

sick birch
#

Yeah, that's why I said buy a VPS

slate swan
#

and how can i install the bot on the vps?

sick birch
#

Easiest way would be to upload your bot's code to github, then git clone <url> on the VPS after SSHing in, cd <dir> into the cloned directory, python3 <filename>.py

slate swan
#

Okay thx

sick birch
#

Preferably also set up CI/CD so you can automatically deploy pushed changes to the production server

slate swan
#

my bot is having problems with the install command, do you have a better command to install python from git?

sick birch
#

What install command?

slate swan
#

for my py bot

sick birch
#

Are you trying to install python?

slate swan
#

the install command dont work

sick birch
#

I'm not sure what install command you're talking about

slate swan
#

yes

sick birch
#

Ah, you can install it from python.org if you're on windows

#

Most linux distributions will have it in their respective package managers

slate swan
#

a link from github to install python

sick birch
slate swan
#

the install command from github with powershell i mean

sick birch
#

Oh, you want to compile from source?

slate swan
#

yes

sick birch
cloud dawn
#

Is there a max amount on SelectOptions?

sick birch
#

Then follow the "Build instructions" in the README

cloud dawn
#

25?

sick birch
#

25, Yes

cloud dawn
#

sheees

austere herald
#

If you want, I can package the entire source code into a zip file just to prove it

#

Of course omitting the token and venv

sick birch
# austere herald πŸ’€

I don't mean to be brash, but most of the time when there's an issue like this, and people say they've tried absolutely everything and they're 100% sure nothing else is wrong but it's still not working, it's something small they missed

austere herald
#

Hm

#

Very well then

#
intents: discord.Intents = discord.Intents.default()
intents.message_content = True
"""Gateway intents to use when connecting to Discord."""
class Versare(commands.Bot):
    def __init__(self) -> None:
        super().__init__(command_prefix=self.get_pre, intents=config.intents)
        self.pool: asyncpg.pool.Pool = None
        
    async def get_context(self, message: discord.Message, *, cls: Optional[type] = None) -> commands.Context:
        return await super().get_context(message, cls=cls or VersareContext)
        
    async def get_pre(self, message: discord.Message) -> list[str]:
        prefix: str = self.prefixes.get(message.guild.id, config.PREFIX)
        return commands.when_mentioned_or(prefix)(self, message)

    async def load_extensions(self, directory: str) -> None:
        for file in Path(directory).rglob("*.py"):
            if "__" not in file.name: # ignore __init__.py
                await self.load_extension(f"{directory}.{file.stem}")
        await self.load_extension("jishaku")

    async def setup_hook(self) -> None:
        """Performs setup tasks for the bot. Initialises dataabase connection, loads extensions, etc."""
        self.pool = await asyncpg.create_pool(config.POSTGRES_DSN_FORMAT.format(**config.private.POSTGRES_CONFIG))
        async with self.pool.acquire() as conn:
            async with conn.transaction():
                with open("db/schema.sql") as f:
                    await conn.execute(f.read())
                self.prefixes: dict[int, str] = dict(await conn.fetch("SELECT id, prefix FROM guilds"))
        await self.load_extensions("cogs")

    async def on_ready(self) -> None:
        print(
            "Versare is ready!\n"
            f"Username: {self.user}\n"
            f"User ID: {self.user.id}"
        )
slate swan
#
if ctx.message.content == any(word in ctx.message.content for word in Snsfw) and ctx.channel.nsfw:
		    await ctx.channel.send(f"Looking for results related to your question {ctx.author.mention}!", delete_after=1)
	      async with ctx.typing():
			  	for j in search(query, tld="co.in", num=1, stop=1, pause=2): 
						await ctx.send(f"\n {j}")
		  	await ctx.send("Have any more questions?,feel free to ask again!", delete_after=10)β€Š
#

unindenation at async with ctx.typing():
(cant cipy pasteerror on my phone)

#

help

#

@slate swan

#

what am i doing wrong

wary shadow
#

Your indentation is incorrect, judging from what you pasted. async with ctx.typeing():

wary shadow
#

Align the indentation with the line above and below it.

cold sonnet
#

if ctx.message.content == any(word in ctx.message.content for word in Snsfw)

#

that's wrong

#

!d any

unkempt canyonBOT
#
any

any(iterable)```
Return `True` if any element of the *iterable* is true. If the iterable is empty, return `False`. Equivalent to:

```py
def any(iterable):
    for element in iterable:
        if element:
            return True
    return False
cold sonnet
#

you see it returns True or False

slate swan
#

still not workingvg

ctx.channel.send(f"Looking for results related to your question {ctx.author.mention}!", delete_after=1)
	      async with ctx.typing():
			  	for j in search(query, tld="co.in", num=1, stop=
cold sonnet
#

missed await

#

await ctx.send() or await ctx.channel.send()

slate swan
#
if ctx.message.content == any(word in ctx.message.content for word in Snsfw) and ctx.channel.nsfw:
		    await ctx.channel.send(f"Looking for results related to your question {ctx.author.mention}!", delete_after=1)
	      async with ctx.typing():
			  	for j in search(query, tld="co.in", num=1, stop=1, pause=2): 
						await ctx.send(f"\n {j}")
		    await ctx.send
#

its aligned

austere herald
#
def mycheck() -> "Check?": # type: ignore # what's the return type here?
    async def predicate(ctx: commands.Context) -> bool:
        return True
    return commands.check(predicate)

...
@commands.command()
@mycheck()
async def mycmd(self, ctx):
  await ctx.send("oi")
``` What's the appropriate return type for commands.checks?#
slate swan
#

its alignedand still doesn't work

wary shadow
slate swan
#

But

#

how

cold sonnet
austere herald
#
  1. Don't use that if comparison, remove ctx.message.content ==
  2. Instead of ctx.channel.send, just do ctx.send
  3. Do not use Replit. Whatever you do
wary shadow
# slate swan

Okay, then the paste is incorrect. That happens, unfortunately. Adds confusion. :(

slate swan
#

its still not wirking

#

how do i fix it

cold sonnet
#

if ctx.message.content == any(word in ctx.message.content for word in Snsfw)...

austere herald
#

any(word in ctx.message.content for word in Snsfw)

#

Just do that

#

Else it's str == bool

slate swan
#

Oh

#
await ctx.channel.send(f"Looking for results related to your question {ctx.author.mention}!", 
delete_after=1)
			  	for j in search(query, tld="co.in", num=1, stop=1, pause=2):
						await ctx.send(f"\n {j}")
		      await ctx.send("Have any more questions?,feel free to ask again!", delete_after=10)β€Š
#

i removed typing

#

wtf how it copy pasted likethat

austere herald
#

What's the code for your search function?

#

WIkipedia lemme guess?

slate swan
#

googlee

austere herald
#

It's blocking :(

slate swan
#

blocking what

cold sonnet
#

blocking async

wary shadow
cloud dawn
#

Could someone provide some info on TextInput it keeps giving me invalid form body ```py
discord.app_commands.errors.CommandInvokeError: Command 'cheese' raised an exception: HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In data.components.2.components.0: Value of field "type" must be one of (2, 3, 5, 6, 7, 8).

slate swan
#

im on mobile

cloud dawn
#

I.. don't like that.

flint isle
#

If I run a command that has a long asynchronous task will the bot accept other commands while that task runs or does it queue the command for after the asynchronous one completes

sick birch
sour peak
#

HI, my bot works fine but I have him on multiple server and the on_member_update
is getting called once x server.
How can I handle it?

BOT

import discord
from discord.ext import commands, tasks
from datetime import datetime
import sqlite3

intents = discord.Intents.all()

bot = commands.Bot(command_prefix='!', case_insensitive=True, intents=intents)
conn = sqlite3.connect('database.db')
c = conn.cursor()


@bot.event
async def on_ready():
    print("-------------------------------")
    print(f"Logged in as {bot.user}")
    print(f"With id: {bot.user.id}")
    print("-------------------------------")


@bot.event
async def on_member_update(before: discord.Member, after: discord.Member):
    if after.status != before.status or after.activity != before.activity:
        print(str(before.display_name) + " was " + str(before.status) +  " and is now " + str(after.status))

        v_user_id = after.id
        v_timestamp = datetime.now().strftime("%d-%m-%Y %H:%M:%S")
        v_username = str(after)
        v_status = str(after.status)
        v_activity = str(after.activity)

        c.execute("INSERT INTO data(user_id, timestamp, username, status, activity) VALUES(?, ?, ?, ?, ?)",(
                    v_user_id, v_timestamp, v_username, v_status, v_activity
                    ))
        conn.commit()

        return

file1 = open('token.txt', 'r')
TOKEN = file1.readline()
bot.run(TOKEN)
wary shadow
#

How do you want to handle it? What outcome do you want?

flint isle
flint isle
unkempt canyonBOT
#

Python Environments

The main purpose of Python virtual environments is to create an isolated environment for Python projects. This means that each project can have its own dependencies, such as third party packages installed using pip, regardless of what dependencies every other project has.

To see the current environment in use by Python, you can run:

>>> import sys
>>> print(sys.executable)
/usr/bin/python3

To see the environment in use by pip, you can do pip debug (pip3 debug for Linux/macOS). The 3rd line of the output will contain the path in use e.g. sys.executable: /usr/bin/python3.

If Python's sys.executable doesn't match pip's, then they are currently using different environments! This may cause Python to raise a ModuleNotFoundError when you try to use a package you just installed with pip, as it was installed to a different environment.

Why use a virtual environment?

β€’ Resolve dependency issues by allowing the use of different versions of a package for different projects. For example, you could use Package A v2.7 for Project X and Package A v1.3 for Project Y.
β€’ Make your project self-contained and reproducible by capturing all package dependencies in a requirements file. Try running pip freeze to see what you currently have installed!
β€’ Keep your global site-packages/ directory tidy by removing the need to install packages system-wide which you might only need for one project.

Further reading:

β€’ Python Virtual Environments: A Primer
β€’ pyenv: Simple Python Version Management

sour peak
sick birch
#

Basically anything that's relatively long running (I/O mostly, non-CPU bound tasks) are asynchronous

wary shadow
flint isle
sick birch
sour peak
sick birch
#

or if you want to be extra, set up a seperate media processing server, and send requests via aiohttp

sour peak
wary shadow
#

I would store the guildId with the event and be done with it. Keep the duplicates. Sort it out in reporting afterward.

stiff fern
#

Can someone help me set up buttons for my suggestion prompt because I'm having a good bit of trouble with it giving me an error and I think it has to do with my python version or something but I'm not sure

#
import discord

from discord import ActionRow, ButtonStyle, app_commands, ui
from discord.ui import Button
from discord.ext import commands, discord
from datetime import datetime
#

I think it has to do with ActionRow and ButtonStyle?

#

and Button

flint isle
flint isle
stiff fern
#

Ty!

flint isle
#

@stiff fern instead use

import discord

from discord import ActionRow, ButtonStyle, app_commands, ui
from discord.ui import Button
from discord.ext import commands
from datetime import datetime
sour peak
stiff fern
# flint isle <@232236405466595328> instead use ```py import discord from discord import Acti...
accept = Button(
            style=ButtonStyle.green,
            custom_id="success",
            label="Accept")

        reject = Button(
            style=ButtonStyle.red,
            custom_id="danager",
            label="Reject")

        action_row = ActionRow(component=[accept, reject]) # <-- here
        suggestion_response.set_author(name=interaction.user, icon_url=interaction.user.avatar)
        await interaction.response.send_message(embed=suggestion_response, ephemeral=True)

        suggestion_message = await review_channel.send(embed=suggestion_embed, Component=action_row)

        @app_commands.Bot.component('success')
        async def accepted(self, interaction: discord.Interaction):
            print('Works!')

Do you know if I'm doing this right? Because it says Component is an unexpected keyword argument

forest oyster
#

hey

#

i downloaded all discord libraries and pipenv and i cant import discord

#

i did it a lot of times, but this time i dont know why i cant import it

flint isle
stiff fern
#

Oh I see no worries

hushed galleon
stiff fern
#

Discordpy documentation makes it kinda hard with all these extra libraries πŸ˜΅β€πŸ’«

flint isle
#

its literally a fork of discord py that has extra stuff in it.

cloud dawn
#

It looks like discord components and dpy 2.0 had ***

stiff fern
#

I think I just organized it wrong

#

imma try and do it this way

cloud dawn
#

I recommend using an up to date library.

stiff fern
#

I mean this should be upto date no?

flint isle
hushed galleon
#

here's a quick example of writing some buttons to send alongside a message (dpy 2.0 and most forks have this): ```py
class MyView(discord.ui.View):
@discord.ui.button(label='Hello')
async def on_hello(self, interaction: discord.Interaction, button: discord.ui.Button):
await interaction.response.send_message('hello there!')

@discord.ui.button(label='Goodbye')
async def say_goodbye(self, interaction, button):
    await interaction.response.send_message(f'Goodbye, {interaction.user}!')

await ctx.send('tell me something', view=MyView())``` further examples of views are in the github: https://github.com/Rapptz/discord.py/tree/master/examples/views
and view documentation: https://discordpy.readthedocs.io/en/latest/interactions/api.html#bot-ui-kit

#

afaik you should never need to assemble the action rows and components yourself

forest oyster
#

hey i have a problem, i have imported all the discord libraries and when i import discord, discord.ext or discord.py it shows a problem with missing imports

hushed galleon
#

can you show the traceback you got when you tried writing from discord.ext import commands?

forest oyster
#

Import "discord.ext" could not be resolved Pylance(reportMissingImports)

flint isle
forest oyster
#

yea thats what i have

flint isle
#

Β―_(ツ)_/Β―

hushed galleon
#

and what does vscode say about the python version in the bottom right corner

flint isle
#

did you use pip to install discord.py? @forest oyster

delicate moat
#

what os are u using cause when i used to use macOS for discord.py it wouldnt work @forest oyster

forest oyster
flint isle
#

uninstall it using all three

#

god only install it once

hushed galleon
#

pipenv manages the virtual environment for you, so you might have 1.7.3 installed on both the global python and autogenerated virtual environment

flint isle
#

lol i use pycharm so i use its pip

hushed galleon
ionic turtle
flint isle
ionic turtle
#

thx!

forest oyster
flint isle
#

anyways back to dnd i go

stiff fern
#

So I can see how they make the buttons here but in this example they place it in a class and then call that class with a message, how would I activate the buttons without having to make it into a class?

#

Would I put it into a actionrow again

ionic turtle
stiff fern
#

Or does it have to be a class

ionic turtle
#

you could do view=self

stiff fern
#

o

ionic turtle
#

but ur indentition is messed up

hushed galleon
stiff fern
ionic turtle
#

this will never be called

stiff fern
#

Because if I put it inside the function how would I get called if that's whats calling it in the first place

#

Or I might just be completely misunderstanding

ionic turtle
#

the

@discord.ui.button
``` decorator *wraps* a function and the callback of the function becomes the button's callback
stiff fern
#

So you press the button and whatever is inside that function runs yes

ionic turtle
#

yes

stiff fern
ionic turtle
hushed galleon
# forest oyster 3.10.5

can you show the full line that vscode highlighted? and also wherever you typed pipenv install discord.py, can you share where pipenv's virtual environment is located by typing pipenv --venv
(sidenote: discord is a mirror of the actual package discord.py but since you already installed discord, you'd stick with that)

stiff fern
#

I have the rest of the code of what happens depending on what button is pressed I just didn't put it together yet because I wanted to get this system working first

ionic turtle
#

you will create an instance of ur class and then send it

#

but that isnt done inside the class

#

its done outside

#

like you could have a sample command like

from xyz import Confirm 


@bot.command(name="hello")
async def hello(ctx: commands.Context):
  await ctx.send('hi', view=Confirm())
forest oyster
stiff fern
ionic turtle
#

no

stiff fern
#

damn

ionic turtle
#

view needs to be a subclass of View/instance

#

you can do

@discord.ui.button(custom_id=...)
#

you can set custom ids in here

stiff fern
#

Right but then whats the point of having a custom id

hushed galleon
ionic turtle
stiff fern
#

o

ionic turtle
#

whihc still work after the bot has been reset/restarted

stiff fern
#

Okay so thats some other thing Im not messing w/ atm

stiff fern
#

So then whats the difference between component= and view=

#

Would they both work for buttons?

ionic turtle
hushed galleon
# forest oyster the pipenv --venv one

do you see a python interpreter listed in the popup dialog with the same "YBN_bot_developing" name when you click the python version in vs code? if so, click that and try running your script in vs code again

stiff fern
#

Oh alright

ionic turtle
#

there really isnt a need to use third party libs rn because all major new features are supported

hushed galleon
#

the effects of monkey patching dpy libs are still being felt to this day

forest oyster
ionic turtle
#

this is the channel i like helping in most but with all the libs/third party things its very challenging 😭

hushed galleon
forest oyster
#

yeap, exactly this

hushed galleon
#

uhhhhhhh can you run pipenv graph to show what packages are installed

#

its hard to tell whats going on without seeing the entire terminal's output

forest oyster
#

yea wait a second

unkempt canyonBOT
#

Hey @forest oyster!

It looks like you tried to attach file type(s) that we do not allow (.bmp). We currently allow the following file types: .gif, .jpg, .jpeg, .mov, .mp4, .mpg, .png, .mp3, .wav, .ogg, .webm, .webp, .flac, .m4a, .csv, .json.

Feel free to ask in #community-meta if you think this is a mistake.

hushed galleon
#

so 9007199254740992

#

... smaller than discord snowflakes

forest oyster
hushed galleon
#

guess vs code is just misconfigured then

#

well your code should run if you type pipenv run python main.py, or whatever you named your script

ionic turtle
#

sad there isnt a big int or long optjon

hushed galleon
#

ah, 2^53 is the mantissa for 64-bit floats used by javascript's number type

stiff fern
#

@ionic turtle another question but how would I update the button to be greyed out when someone presses it? I realize self.stop() makes it where it'll basically not respond when you press it but isn't there a way to make it where you can't press it at all or something cleaner?

ionic turtle
#

and then edit the message

stiff fern
#

How do you set it to disabled

#

self.value = False?

sick birch
#

Yes, but keep in mind that only sets the view classes' value property to False. It doesn't actually disable it on discord

#

You'll have to re-send the view for it to take effect

ionic turtle
# stiff fern self.value = False?

if you wanted to disable all of them use like a loop

@discord.ui.button
async def xyz_button(
  self, 
  interaction: discord.Interaction, 
  button: discord.ui.Button
):
  ...
  for item in self.children:
    item.disabled = True
  await interaction.edit_original_message(view=self)
stiff fern
#

Oh so the loop is always at the end of the script

ionic turtle
#

you could do at begining it doesnt matter

stiff fern
#

Oh alright

hushed galleon
# stiff fern self.value = False?

the confirm.py example you saw earlier uses self.value as an easy way for the command to tell whether the user clicked confirm or cancel, but its merely a custom attribute that the developer of that example chose to use; you could write any attribute that doesnt conflict with whatever's documented in View like self.user_id (say for an interaction_check() to make sure the view is only usable by one person) or self.bot (maybe to access an attribute in your bot, like a database)

stiff fern
#

So what does self.stop() do

hushed galleon
#

it makes your bot forget that view ever existed

stiff fern
#

Oh alright

hushed galleon
#

if someone clicks on it afterwards, the bot receives an interaction pointing to a message+custom_id that it isn't aware of and silently ignores it

stiff fern
#

So here's a question, edit_original_message edits the interaction that's inside the button function but how would I edit the actual original message which would be the suggestion embed

#

Because you can do self.children I dont know if theres a self.Parent that works for that too lol

ionic turtle
ionic turtle
#

no need to guess attributes

#

and no theres no self.parent because self is the 'parent' of the children items

#

!d discord.ui.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.
stiff fern
#

It should be the message the view is attached to but it's giving me an error?

#

i shall look

stiff fern
ionic turtle
#

try

message = await interaction.original_message()
await message.edit(...)
#

note this is an http request

hushed galleon
stiff fern
#

Still errors and I think it's because I moved the interaction within the actual button press function above the edit and it's trying to sync the original message with that message

hushed galleon
#
  • send_message() makes it refer to your new message
  • edit_message() and defer() makes it refer to Interaction.message

with send_message(..., ephemeral=True), you can even edit it afterwards using original_message()

stiff fern
#
@discord.ui.button(label="Reject", emoji="![No](https://cdn.discordapp.com/emojis/986643106835353691.webp?size=128 "No")", style=ButtonStyle.red)
            async def reject(self, interaction: discord.Interaction, button: discord.ui.Button):
                
                for item in self.children:
                    item.disabled = True
                    
                message = await interaction.original_message()
                await message.edit(view=self)

                await interaction.response.send_message('Cancelling', ephemeral=True)

        suggestion_response.set_author(name=interaction.user, icon_url=interaction.user.avatar)
        await interaction.response.send_message(embed=suggestion_response, ephemeral=True)

        suggestion_message = await review_channel.send(embed=suggestion_embed, view=Buttons())
stiff fern
#

And because it was using that one I moved it up so it wouldn't use it and now it basically can't find anything to edit lol

hushed galleon
stiff fern
#

Oooh

#

Oh damn I thought response was just something you had to put to use edit_message

#

damn - that makes sense too

#

Haha it works now

#

Is there a way to do the equivalent of self.self lol

hushed galleon
#

what does that mean?

#

self.self seems pretty arbitrary in the context of OOP

stiff fern
#

For example I need access to this Answer_one input

#

From the modal inside the class of the button functions

#

Normally if they were outside of that class I could do self.answer_one

#

But since its basically another scope in, I can't do that so I was wondering if there's some other method

hushed galleon
#

its unpythonic to nest a class in a method, but whether you put it outside or not, you can define a custom init method for your Buttons class with a parameter to store answer_one

stiff fern
#

I only did it because it was the only way I could figure out to actually get the buttons to work 😬

hushed galleon
#

for example: ```py
class SuggestionView(discord.ui.View):
def init(self, suggestion_text, *args, **kwargs):
super().init(*args, **kwargs)
self.suggestion_text = suggestion_text

@discord.ui.button(...)
async def accept(self, interaction, button):
    # use self.suggestion_text here```
stiff fern
#

Oh okay I see

hushed galleon
#

although are you sure you need it? im guessing the suggestion embed you'll be sending with Buttons will already have the answer in its description

#

in which case you can access the existing embed with interaction.message.embeds[0] and simply change the parts you're updating, like the title/color, then edit the message with the embed passed back

stiff fern
hushed galleon
#

also note that dpy will overwrite the answer_one attribute with a string when on_submit is called, so you have to access the label through the class object itself, i.e. suggestion_modal.answer_one.label (whatever the user typed would be in self.answer_one)

stiff fern
#

Ty

#

Do you know how I would get the user who interacted with the button

#

interaction.user?

hushed galleon
#

ye

stiff fern
stiff fern
hushed galleon
#

put it in a variable for easier use, then whatever parameters you can pass to discord.Embed() can also be set with =

stiff fern
#
embed = interaction.message.embeds[0]
embed.label
hushed galleon
#
embed = <the existing message embed>
embed.title = 'Suggestion Denied'
embed.set_author(...)```
stiff fern
#

nvmlol

stiff fern
#
class Buttons(discord.ui.View):
            
            def __init__(self, answer_one, *args, **kwargs):
                super().__init__(*args, **kwargs)
                self.answer_one = answer_one

Tried putting self and answer_one but it still returns the same error?

hushed galleon
stiff fern
#

I've tried addingn self.answer_one to the class but that also gave me an error

#

Unless thats not what you meant

#

OH - got it thank ya

slate swan
#

The channel's so dead at this time psychcat

stiff fern
#

I mean I can ask a million questions but I try not to spam the channel for stuff I can figure out in due time lol

#

Like rn I dont understand why the top for loop doesn't work but the bottom one does

stiff fern
#

oh lol

#

that doesn't fix my issue but ill change it

slate swan
#

Tell more briefly

#

Any errror

stiff fern
#

So I have 2 buttons,

If I press the Reject button (The bottom one in the example), it'll properly disable both buttons so you can't interact with either

#

If I press the accept button (The top one) it still lets me press both buttons and doesn't disable them

slate swan
#

Sry gtg school vehicle camed

stiff fern
#

no worries lol

ionic turtle
#

from the decorator

stiff fern
# ionic turtle Show full code for top one

I realized I was getting an error because the response was trying to respond to itself multiple times or something like that and now I'm trying to write it the same way the reject code is written because ofc that one works but its saying I need to define the variable even though I didnt do it for the rejection one but yeah Ill send it even tho it may be long

#
@discord.ui.button(label="Accept", style=ButtonStyle.green)
            async def accept(self, interaction: discord.Interaction, button: discord.ui.Button):
                
                user_name = str(interaction.user.name)

                # Embed for staff channel
                suggestion_embed = discord.Embed(
                    title='Suggestion Accepted',
                    description=f'**{self.answer_one.label}**\n{self.answer_one}',
                    timestamp=datetime.now(),
                    color=0x49ba8b  # Green
                )

                suggestion_embed.set_author(name=interaction.user, icon_url=interaction.user.avatar)
                suggestion_embed.set_footer(text=f'Accepted by {user_name[0]}')

                # Embed for suggestion channel
                public_suggestion_embed = discord.Embed(
                    title="New Suggestion",
                    description=f'**{self.answer_one.label}**\n{self.answer_one}',
                    timestamp=datetime.now(),
                    color=0x3f6782  # Default
                )

                public_suggestion_embed.set_author(name=interaction.user, icon_url=interaction.user.avatar)
                public_suggestion_embed.set_footer(text=f'Accepted by {user_name[0]}')

                # Updating suggestion in staff channel
                await suggestion_message.edit(embed=suggestion_embed)

                # Getting suggestion channel
                suggestion_channel = interaction.guild.get_channel(986755419894579261) or await interaction.guild.fetch_channel(986755419894579261)
                suggestion_message = await suggestion_channel.send(embed=public_suggestion_embed)

                # Adding UpVote/DownVote reactions
                await suggestion_message.add_reaction('![UpVote](https://cdn.discordapp.com/emojis/986643126796042320.webp?size=128 "UpVote")')
                await suggestion_message.add_reaction('![DownVote](https://cdn.discordapp.com/emojis/986643070864994416.webp?size=128 "DownVote")')

                for item in self.children:
                    item.disabled = True
                await interaction.response.edit_message(view=self)
                self.stop()
ionic turtle
stiff fern
#

Are you not suppose to everything in the callback?

ionic turtle
#

and replace the

await interaction.response.edit_message(...)
```with
```py
await interaction.edit_original_message(...)
ionic turtle
stiff fern
#

Oh alright

hushed galleon
ionic turtle
#

i think the adding reactions is adding time and may eventually exceed 3 seconds

#

but yeah, error pls ^^^

hushed galleon
#

yeah id agree with that too

stiff fern
stiff fern
ionic turtle
stiff fern
#

Nvm I misspelled response

#

πŸ˜…

ionic turtle
#

ohh

hushed galleon
#

hmm your screenshot doesnt seem to show it was misspelled

stiff fern
#

It works now thank you :)

stiff fern
ionic turtle
#

does it work with the defer?

stiff fern
#

It does

hushed galleon
ionic turtle
#

πŸ‘

hushed galleon
#

i would just move the edit_message to before the send() and add_reaction(), and also update the embed through the interaction

#

although this way would need a few permission checks to make sure the bot can actually send messages/reactions before disabling the buttons

stiff fern
#

So what would be a better way of doing this on an optimization standpoint

#

Because it does take a solid second for the buttons to get greyed out and if I spam it then multiple prompts send which isnt a issue now but I'm just planning on if I add more if it's going to take longer each time what the proper way is

hushed galleon
#

id go with the approach i described, i.e. check permissions first, then grey out the buttons + update the embed and do whatever afterwards

#

unless you really want it to be robust, then you can further reduce what your button must do so it stays under the 3 second limit, e.g. only sending the suggestion message and responding afterwards

#

that way you only disable the buttons when you know that message was sent, and if your bot fails to add the reactions you can send a followup warning so at least the moderators are able to add it at a later time

#

oh and the user can't click before the bot responds

#

i think its pretty easy to over-engineer this

stiff fern
#

Would I just call another class/function within that class

hushed galleon
#

nah it can still be in the same callback, im just saying the response to edit the view/embed would happen first and then sending/reacting happens after

stiff fern
#

Oh that makes sense

stiff fern
hushed galleon
#

with this approach you just need edit_message(), no defer() or edit_original_message()

stiff fern
#

Should the defer be in front of that?

#

Oh

hushed galleon
#

also edit_message can take an embed= parameter

stiff fern
#

Oh alright

hushed galleon
#

i recommend you update the embed in the interaction so you aren't double editing the message

stiff fern
#

Wouldnt I have to edit it after disabling it so it shows on discord?

#

Or else wouldn't it still be delayed

hushed galleon
#

yea

#

permission checks
disable and edit
send public suggestion
add reactions

stiff fern
#

πŸ‘

#

Do you know how I would make the bot only reply to direct replies to its message

#

The things I'm finding are if someone sends a message regardless of they replied to it or not

hushed galleon
#

!d discord.Message.reference

unkempt canyonBOT
#

The message that this message references. This is only applicable to messages of type MessageType.pins_add, crossposted messages created by a followed channel integration, or message replies.

New in version 1.5.

hushed galleon
#

check if reference.resolved is available and was authored by your bot

stiff fern
#

ty

dull knot
#

It doesn't DM on Join

#

These are the Imports plus the member intent being enabled

#

Here's what was written in the console

#

Ping me if you guys can helpsadcry

#

Also, any resources you guys can give me to fix this also helps. sadcry

#

I'll just come back again for questions if needed

hazy oxide
hazy oxide
dull knot
dull knot
hazy oxide
#

Do u enable intens from discord developer portal?

dull knot
#

Could it have something to do with the bot.listen decorator?

Last I used it, it also didn't work

dull knot
hazy oxide
slate swan
dull knot
hazy oxide
dull knot
hazy oxide
#

On bot.event

slate swan
#

your error is related to the message content intent lmao

hazy oxide
slate swan
#

what about dev portal?

hazy oxide
#

He alr enabled intents

dull knot
#

Still didn't work

#

I enabled intents

slate swan
#

ah i know lmfao

#

youre using discord.Intents in your bot

dull knot
#

Lemme check

slate swan
#

and your bot uses disnake :))

dull knot
#

Ahh. So there's a difference?

#

sadcry Finally.

#

How should I go about it?

slate swan
#

nah nah

#

you have 2 instances of bots right?

dull knot
#

I think just one

#

Oh wait

slate swan
#

You have a disnake bot and discord bot

#

youre using 2 different classes

dull knot
#

from disnake import CommandInteraction, Message
from disnake.ext.commands import Bot
from discord.ext import commands
from discord import Intents

import os

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

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

bot = Bot()

These?

slate swan
#

yes just remove bot = Bot() and the import and replace discord with disnake

#

and your problem should be solved

dull knot
#

Ah. Lemme try

#

Oof. Got temporarily rate limited

#

sadcry Will try it again in a few.while

hidden snow
#

hey how can i get a users discord tag, for example i want to use something like member.display_name but with the numbers at the end
further ex
i want SnowZillin#4335

slate swan
slate swan
#

the str dunder of the class should return the whole tag

hidden snow
#

ok ill try that

#

oh dope ty

dull knot
slate swan
#

youre welcome guys ;))

dull knot
#

Also, guys. One more thing

#

Flask is what's often used to make bots online, right?

Can u guys, send me a resources about it or smthh_MyBad I'd like to learn how it works in keeping bots alive

slate swan
#

not quite

rain olive
#

vps

slate swan
#

people just use flask and keep alive to keep the replit container running

rain olive
#

use vps instead of replit

slate swan
dull knot
#

I'll probably just watch And read more articles later. For now, I'll try Testing some stuff out. Might be too much to handle for me rnh_MyBad

dull knot
#

Yeah. sadcry

rain olive
#

can u afford a vps

#

Β£3-5/mth

dull knot
#

Nah. What's a VPS?

Still just a month-ish in on coding so Still not very familiar with most terms

rain olive
#

server, u can keep ur bot alive there

#

most ppl use vps

dull knot
#

Ah. Nah. I don't really ask my parents for stuff. I doubt they'd buy it anywyas

#

Well, for now, I'll probably just get used to how to make commands. And eventually when I think I have enough understanding, will learn how to make it alive

rain olive
#

i see

#

replit has shared ip => youll get ratelimited alot

slate swan
rain olive
#

dont ping me 4 dat lol

slate swan
#

the definition of the term is a Virtual Private Server so atleast say what the term means πŸ—Ώ

rain olive
#

full form* not definition, but sure

paper sluice
rain olive
#

im not discussing further

slate swan
#

im pretty sure changing words that aim for the same point doesnt really matter but ok

#

you do you

stiff fern
#

Ideas on what this means?

#

I'm not sure what lines its referring too because I only have 200 so I don't know what portion of code to share

vocal snow
stiff fern
#

ok ty

vocal snow
#

the exception mentions edit_message so presumably it's that

stiff fern
#

ty!

#

@vocal snow do you have an idea on how I can reference a difference interaction within a separate interaction? Thats where the error is coming from

torn sail
stiff fern
#

o

#

tbh thats how I saw it written even where so I didnt even think to do that

#

you can reference them globally though?

celest hound
#

hey

spring sapphire
#

Hey guys!
https://github.com/code-chaser/dex :- a discord bot created by me πŸ’œ;
It's my first try at python - all kinds of reviews are most welcome!
Most importantly, I'd be really grateful to anyone doing code review;
Thanks in advance! 😊

GitHub

This is DEX, a multi-purpose discord music bot made using discord.py. - GitHub - code-chaser/dex: This is DEX, a multi-purpose discord music bot made using discord.py.

vocal snow
#
        v = cast(Voice, self.guild.voice_client)
        if v is None:
            raise NoVoiceException
        return v
``` is this cursed?
pliant gulch
#

It makes more sense to cast after checking if it’s None

vocal snow
#

ok ty!

stiff fern
#

Question, how am I suppose to reference the value of label? Do I need to to tostring(label) or something?

#

Because thats what it comes out like

vocal snow
vale wing
# spring sapphire Hey guys! https://github.com/code-chaser/dex :- a discord bot created by me πŸ’œ; ...

From what I have already noticed

  1. Very cool design

In your bot class there are some things you could improve

  1. Never seen anyone using UPPER_SNAKE_CASE for attributes (I mean DATABASE_CONNECTION), it's typically used for classvars
  2. I wouldn't recommend storing links as classvars of bot class. It's better to create a module called constants and put them all to there or even use some other system
  3. Doing SQL queries like this
con.execute('INSERT INTO tbl (id, name, surname) VALUES (50, \'man\', \'sus\')')```
is a bad idea. SQL insertions exist (or whatever they are called)
```py
con.execute('INSERT INTO tbl (id, name, surname) VALUES ($1, $2, $3)', 50, 'man', 'sus')```
4. There's a better way of making an error handler I typically use to avoid all those if-elif-elif-elif-... constructions. You can check it out here https://github.com/Exenifix/AIAS/blob/master/utils/errors.py (and yeah I do have small mistake in members getting)
GitHub

AIAS (Artifical Intelligence AntiSpam) is an open-source Discord bot that has innovative moderation features, such as nextgen word filter and AI-based spam detection. - AIAS/errors.py at master Β· E...

stiff fern
#

Ty

vale wing
#

And you could also setup some better logging

#

!pypi exencolorlogs you may use ready solution or create something by yourself

unkempt canyonBOT
vale wing
#

what for did I link personal purpose package

harsh atlas
#

Hey guys i have a problem with discord.py i have made a custom prefix (from tutorial) and i will like to make when the member mention the bot it will send the prefix and im using modules so here is my main.py code

#
# Prefix
def get_prefix(client, message):
  with open("prefix.json", "r") as f:
    prefixes =json.load(f)

  return prefixes[str(message.guild.id)]
  
# Prefix, Owner, Disable default help command
client = commands.Bot(command_prefix = get_prefix, owner_id = 468194427903410176, help_command=None)

# When Roumy is online send to console `Roumy is online` and set status `Listenis to ?help`
@client.event
async def on_ready():
    await client.change_presence(activity=discord.Activity(
      type=discord.ActivityType.listening, name="@Roumy", help_command=None))
    print("Roumy Is Online!!")

# Add prefix when bot join a server
@client.event
async def on_guild_join(guild):
  with open("prefix.json", "r") as f:
    prefixes = json.load(f)
    
  prefixes[str(guild.id)] = ","

  with open("prefix.json", "w") as f:
    json.dump(prefixes, f, indent = 4)

# Remove prefix when bot leave a server
@client.event
async def on_guild_remove(guild):
  with open("prefix.json", "r") as f:
    prefixes = json.load(f)
    
  prefixes.pop(str(guild.id))

  with open("prefix.json", "w") as f:
    json.dump(prefixes, f, indent = 4)
#
# Set Prefix command
@client.command()
@commands.is_owner()
async def prefix(ctx, prefix):
  with open("prefix.json", "r") as f:
    prefixes = json.load(f)
    
  prefixes[str(ctx.guild.id)] = prefix

  with open("prefix.json", "w") as f:
    json.dump(prefixes, f, indent = 4)

  await ctx.reply(f"Prefix change to: {prefix}")
  
@prefix.error
async def prefix_error(ctx, error):
  if isinstance(error, commands.CheckFailure):
    
    prefixError = discord.Embed(
      title = "Permission Denied",
      description = "Missing `Administrator` permission",
      colour = 0xeeffee)
    
    await ctx.reply(embed = prefixError)
    
@prefix.error
async def prefix_error(ctx, error):
  if isinstance(error, commands. MissingRequiredArgument):
    
    prefixError2 = discord.Embed(
      title = "Error",
      description = "Please specify the prefix - `prefix <prefix>`",
      colour = 0xeeffee)
    
    await ctx.reply(embed = prefixError2)
#

Sorry if i have done something whorg im new to discord.py

#

Btw i have set the set prefix command for owner only because i already add it to my main bot

#

Here is my mantion command:

import discord
from discord.ext import commands

class Moderation(commands.Cog):

  def __init__(self, client):
    self.client = client

  @commands.Cog.listener()
  async def on_message(self, message):
        if message.content.startswith("@outer quarry"):
          
          mention = discord.Embed(
          title = "The prefix is `,help`",
          colour = 0xeeffee)
          
          await message.channel.send(embed = mention)

def setup(client):
  client.add_cog(Moderation(client))
vale wing
#

Json database cring

hidden snow
#

how would i set a variable to a message if somebody inputs a certain starter phrase
for example
@client.command(
async def setname(message):
new = message.context.replace('!setname ','')

vocal snow
#

which library is this?

paper sluice
vocal snow
#

*discord.ext.commands.Context

paper sluice
#

oops

verbal flicker
#

how do i get textchannel name by command

hazy oxide
#

You mean get the text channel?

shrewd apex
#

!d discord.utils.get

unkempt canyonBOT
#

discord.utils.get(iterable, /, **attrs)```
A helper that returns the first element in the iterable that meets all the traits passed in `attrs`. This is an alternative for [`find()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.utils.find "discord.utils.find").

When multiple attributes are specified, they are checked using logical AND, not logical OR. Meaning they have to meet every attribute passed in and not one of them.

To have a nested attribute search (i.e. search by `x.y`) then pass in `x__y` as the keyword argument.

If nothing is found that matches the attributes passed, then `None` is returned.

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

Changed in version 2.0: The `iterable` parameter supports [asynchronous iterable](https://docs.python.org/3/glossary.html#term-asynchronous-iterable "(in Python v3.10)")s...
full valley
#

What’s the best way to handle mutes, so if I update my bot the mute timer tasks aren’t lost

slate swan
#

just use timeouts. or a database

fresh notch
#

discord.ext.commands.errors.CommandRegistrationError: The command help is already an existing command or alias.

@bot.event
async def on_ready():
    print('Running:', bot.user)
    await bot.change_presence(status = discord.Status.online, activity=discord.Game(name='Cyberpunk2077'))
    bot.remove_command('help')
paper sluice
#

commands are loaded before the on_ready event, so you need to remove it outside

fresh notch
#

oh

paper sluice
#

or just do

bot = commands.Bot(..., help_command=None)
slate swan
#

!d discord.ext.commands.Bot use the status and activity kwarg in this

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.
fresh notch
fresh notch
#

but ill do this thanks

slate swan
#

even if you want to change later, on_ready wont be helpful

fresh notch
#
@bot.command()
async def help(ctx):
    embed = discord.Embed(title="Help", description="Commands", color=0x1abc9c)
    embed.add_field(name=">help", value="Shows this message", inline=False)
    embed.add_field(name=">ping", value="Shows the bot's ping", inline=False)
    embed.add_field(name=">say", value="Makes the bot say something", inline=False)
    embed.add_field(name=">tad", value="Terry A. Davis", inline=False)
    embed.add_field(name=">whois", value="Shows the user's info", inline=False)
    embed.add_field(name=">ip", value="Gives information about any ip", inline=False)
    embed.add_field(name="Features", value="Logs deleted and edited messages in [#995965561248940092](/guild/267624335836053506/channel/995965561248940092/)/n Sends a funny when 'troll' or 'ripwin' is mentioned'/n Deletes swear words", inline=False)
    await ctx.send(embed=embed)```
paper sluice
#

what library?

slate swan
#

😭 my pc is not starting

paper sluice
#

πŸ”¨ use this and try

slate swan
#

the startup cable that connects with main switch is losse

slate swan
#

I need to tight it ;-;

#

why dont people subclass πŸ˜”

fresh notch
slate swan
#

Nitro πŸ‘€

dusky pine
#

ash nitro flex

slate swan
#

cause not everyone is you ash

fresh notch
#

this is my second day using the discord module

#

i barely understand stuff

slate swan
slate swan
slate swan
slate swan
slate swan
#

4?

dusky pine
#

just tell your users to pull up the slash command menu

slate swan
#

all of them use discord namespace

#

nextcord allows both^

slate swan
#

what what what what

paper sluice
#

nitro πŸ‘€

slate swan
#

smh

fresh notch
dusky pine
#

ash buy me nitro pls 😍 πŸ™

slate swan
#

yeah its fine then

slate swan
#

they stopped when discord.py continued with development kek

#

i liked their codebase tho

slate swan
slate swan
#

!paste here

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.

slate swan
#

!pip discord2

unkempt canyonBOT
slate swan
#

totally not pycord in disguise

slate swan
slate swan
#

welcome