#discord-bots

1 messages · Page 117 of 1

dapper bluff
#

thx

primal token
#

I cant answer a question with a yes or no if it cant be answered with a yes or no as it doesnt make sense on its own

dapper bluff
#

This has nothing I need

hollow agate
#

You read it

dapper bluff
#

I did

#

Nothing is there that I need

hollow agate
#

& check if the argument has a mention and boom. That’s your check

dapper bluff
#

IM ASKING HOW TO DO THAT

#

you claim to be "helping" youre doign the worst job at it

hollow agate
#

I’m not trying to spoon feed. You need to learn how to read the documents and I’m trying to get you to the point where you don’t have to ask these questions.

Try to make a check and tell me where it goes wrong.

dapper bluff
#

I FUCKING READ THE DOCUMENTS YOU ANNOYING ASSHOLE

hollow agate
#

I’m not going to give you the correct answer, but I’ll help you through it

dapper bluff
#

I DONT KNOW WHAT TO DO NOW

#

I HAVE IT OPENED WHERE TF DO I GO

primal token
hollow agate
#

Start by getting your message set…

#

Once you get your message attribute set, you can then use the .mentions attribute

dapper bluff
#

What tf is a message attribute?

hollow agate
#

Ctx is your message attribute basically

blissful lagoon
#

!mute 269990152368029697 2d This is the second time you've been extremely rude to someone trying to help you. Change your attitude before returning or you'll be banned.

unkempt canyonBOT
#

:incoming_envelope: :ok_hand: applied mute to @dapper bluff until <t:1667344270:f> (2 days).

hollow agate
#

He should learn how to do basic Python and read documents 😅

#

…but I guess it’s not that basic

sick birch
#

Eh, their usecase could be considered semi-difficult

hollow agate
#

Fair, this case is pretty interesting

sick birch
#

From what I gather, they wanted something like: typing.Union[typing.Literal[...], ...]

#

And then a few if/elifs with isinstance checks

hollow agate
#

I don’t know why they disliked the idea to type hint it though

#

He kept saying that it wasn’t what he wanted to do shrug

sick birch
#

Probably because it errors out, and they wanted more of an if/else approach

#

people tend to like LBYL over EAFP

primal token
hollow agate
#

Fair, it’s much easier with Union or Literal

sick birch
#

right you are

primal token
hollow agate
#

Oh well, in two days we’ll see what he has pepe_happy

sick birch
# primal token What does LBYL and EAFP mean?

LBYL: look before you leap - traditionally an if/else approach:

can_do_something: bool = ...
if can_do_something:
  do_something()
else:
  error()

EAFP: easier to ask for forgiveness than permission:

try:
  do_something()
except:
  error()
primal token
#

ah i see, interesting terms

sick birch
#

that's just what they're called ¯_(ツ)_/¯

primal token
#

I've actually never seen the usage of them lol

sick birch
#

Not the specific terminology, no. But the concept is quite common

primal token
#

yep

sick birch
#

E.g "would it be better for me to use an if/else here or a try/except?"

#

"Should I use try/except with dict [] notation, or use .get()?"

#

That's actually a prime example of the difference

primal token
#

I always use LBYL but it always depends on the use case

pliant gulch
#

I never seem to raise errors

sick birch
#

If the operation you want to do doesn't raise errors, then LBYL is the better approach (e.g .get())

#

It just depends really

#

Unlike [] notation which does raise errors, where you'd use EAFP

pliant gulch
#

[] doesnt always have to raise an error e.g via indexing

sick birch
#

You could probably write __getitem__ in such a way that it behaves like .get(). Probably not recommended, but you can do all sorts of funky stuff

pliant gulch
#

!e ```py
foo: list[str] = ["foo", "bar", "baz"]
if buffer := foo[3:]:
print(buffer[0], "shouldnt")

if buffer := foo[2:]:
print(buffer[0], "yes")

unkempt canyonBOT
#

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

foo yes
pliant gulch
#

did an oopsie with my slice but you probably see what I mean

indigo pilot
#
[ ❌ ] Failed to load cog: cogs.user.customizeation
Error log: Extension 'cogs.user.customizeation' raised an error: KeyError: 'serverid'
[2022-10-30 20:10:53] [ERROR   ] discord.ext.tasks: Unhandled exception in internal background task 'game_simonsays_creation'.
Traceback (most recent call last):
  File "C:\Users\kaelm\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\tasks\__init__.py", line 239, in _loop
    await self.coro(*args, **kwargs)
  File "C:\Users\kaelm\PycharmProjects\SimonSays\cogs\games\simonsays\gameCreation.py", line 50, in game_simonsays_creation
    guild = self.bot.get_guild(int(guild["_id"])) or self.bot.fetch_guild(int(guild["_id"]))
TypeError: '_asyncio.Future' object is not subscriptable```

anyone know why?
#

TypeError: '_asyncio.Future' object is not subscriptable
ive never seen this error

sick birch
#

looks like you're re-assigning

indigo pilot
#

loop var

slate swan
#

is there any way i can make it so when i do my command ">>avatar @" it can give a download link to the avatar?

indigo pilot
indigo pilot
slate swan
slate swan
indigo pilot
slate swan
#

well i wanna try and make it send a download link kinda how it shows display name, seen it before just wondering if its possible

#

to download the avatar

indigo pilot
#

fixed by doing guildVar = self.bot.get_guild(int(guild["_id"])) or await self.bot.fetch_guild(int(guild["_id"]))

but now i cant do guild.members i get <discord.utils.SequenceProxy object at 0x0000027FB9177430>

sick birch
indigo pilot
#

since i wasnt sure if you can get a guild when not in so was just confirming

#

copiolet gave me that so might be wrong, i forget if its self.bot.user

sick birch
#

i'm confused

#

what are you trying to do with guild.members? just print it to console?

indigo pilot
#

my code isnt running at

#

if self.bot.user not in guild.members

sick birch
#

You might want to check the len() of it instead

indigo pilot
#

without any error

sick birch
indigo pilot
#

o

sick birch
#

though i don't really see the point

#

if you have the guild object you're in it

indigo pilot
#

one more question

#
            games = await self.bot.database.games.find({"guild_id": guildVar.id, "game": "simon_interactive"}).to_list(None)
            check = True
            while check:
                for game in games:
                    if game['status'] == 'running':
                        check = False
                        break
                    if game['status'] == 'queueing':
                        check = False
                        break

            print(5)
            if check == False:
                continue```

i got this to get all games with the guild ID and game type, im trying to do it if any of them are status = running or queueing, continue the loop (theres a bigger loop that this code is in)

is th ere a btter way to do this as that way dosnt work bc it just while's forever
#

for guild in guilds
games = await blah blah blah

#

i need to continue the for guild in guilds loop if one of the two game statuses are true

slate swan
#

how do i fix this

#

help please

young pendant
unkempt canyonBOT
young pendant
chilly dove
# slate swan help please

you set a minimum amount of values the user can specify to 5 but you never passed in 5 or more options

young pendant
#

I cant find any mistake I have made in the code, it would be nice, if someone could help me

slate swan
#

I asked him earlier to send his code for the view but he just resent the same img , pretty sure he just copied someone else’s code

slate swan
chilly dove
#

literally just did a test on my bot and got the exact same traceback setting the min values to higher then the amount of options

indigo pilot
#

since channel.history wont take a timestamp for after/before, anyone know how i can convert unix / timestamp to datetime obj

prisma prism
#

Hi Guys! Does anyone know a way to check if a user has a role, but with a list of roles?

indigo pilot
#

lmao

sick birch
indigo pilot
#

any

#

that exists what 😭

prisma prism
#

thank you!!

sick birch
#

Usually I'll create a utility function in my projects:

def has_any_role(member: discord.Member, roles: list[discord.Role]) -> bool:
  return any(role.id in role_ids for role in member.roles)
#

The name may clash so you might want to change that if possible

#

Or just use the built in check if that's desirable

young pendant
sick birch
#

do you have code?

#

it would be helpful to see it

young pendant
sick birch
#

ty

#

didnt notice that

young pendant
#

np

sick birch
#

i'm guessing the issue is:

for x in self.roles_of_team[guild_id]:
  val = val + f"<@&{x}>\n"

x is a tuple

#

you could try f"<@&{x[0]}>"

young pendant
#

okay, thanks

#

doesn't work Sadge

young pendant
#

yeah

sick birch
#

did you replace all instances of x with x[0] or just one?

young pendant
#

the only reason it does not ping team is because of this stupid ","

sick birch
#

not just that

#

the (,) marks it as a tuple

young pendant
#

normally the id should be <@&id>

sick birch
#

x is a tuple and it's being converted to a string

sick birch
young pendant
#

hmm

#

I'm so confused Sadge

sick birch
#
    async def info(self, guild_id):
        embed = discord.Embed(title="Info", color=discord.Colour.from_rgb(64, 118, 227))
        if self.roles_of_team[guild_id] != [] and guild_id in self.team_roles.keys():
            val = ""
            for x in self.roles_of_team[guild_id]:
                val = val + f"<@&{x}>\n"
            embed.add_field(name="Teamrolle:", value=f"<@&{self.team_roles[guild_id]}>", inline=False)
            embed.add_field(name="Rollen:", value=val)
            return embed
        elif self.roles_of_team[guild_id] != []:
            val = ""
            for x in self.roles_of_team[guild_id]:
                val = val + f"<@&{x}>\n"
                print(x)
            embed.add_field(name="Teamrolle:", value="keine Rolle festgelegt", inline=False)
            embed.add_field(name="Rollen:", value=val)
            return embed
#

you changed x both times, yes?

pliant gulch
#

You need to makesure inside of init_roles that you flatten your record from the SELECT query

#
            self.cursor.execute(f"SELECT id FROM roles WHERE guild_id = {guild.id};")
            
            for role_id in self.cursor:
                self.roles_of_team[guild.id].append(role_id[0])
``` Like, can you print `role_id[0]` here?
#

To make sure it's either not a tuple or is one

#

Because this issue only happens when you reset meaning it has to be in here right?

young pendant
#

yeah, both x changed to 0

young pendant
#

little confused

pliant gulch
#

When you restart the bot the issue appears, this mean either you populate your cache INCORRECTLY which causes your roles_of_team to become dict[int, list[tuple[int, ...]]] when you actually want dict[int, list[int]]

#

The other issue that could be happening is you actually mutating the cache with incorrect data which I don't see from a scan

#

So your query must've produced a tuple

young pendant
#

how do I fix it?

pliant gulch
#

Well first of all confirm it

young pendant
#

Just a question, its my first time working with python since one year, what do you mean by print role_id[0]

#

?

#

@pliant gulch

hollow agate
#

Just do print(role_id[0]) as what I assume it’ll be a debug.

#

It’ll give us the first value of role_id in the database

young pendant
#

@hollow agate are you still there?

hollow agate
#

Yep!

young pendant
#

I printed the ID of the role TEAM which is not displayed properly after restart

#

(905095402448101406,)

#

I`m getting this

#

if the , would not be there, this bot would work

hollow agate
#

Ah! Okay

young pendant
#

The bot just saves the ID wrong

#

the other id grabbing function works fine

hollow agate
#

That’s a tuple, you just have to remove it… it’s been a very long time since I’ve done this, so let me eval and test it before giving you a wrong answer 😂

hollow agate
#

You’re welcome! Allow me ~10 mins

young pendant
#

yeah, no problem

hollow agate
#

How are you storing the ID?

#

Maybe it can be easier to remove the tuple from the storing method rather than remove it when we fetch it

young pendant
#

Should I send you the code?

hollow agate
#

Sure!

young pendant
#

there you go

#

The name is role_ids.db

hollow agate
#

What line are you storing/committing the ID?

young pendant
#

51 I think

#

self.db.commit()

#

If I'm wrong tell me

#

A n

#

Ah no

hollow agate
#

Where do you store the IDs? lol

#

That commits the creation of the database (i think)

young pendant
#

you mean, when I used the /change_team_role command?

#

Line 100 - 109 is the part where the bot grabs the id from the role

hollow agate
#

Got it, there can you put a small debug and just print(role.id)?

hollow agate
young pendant
#

works fine

hollow agate
young pendant
#

Yep, but after restart, this is not the case

hollow agate
#

What happens before and after a restart?

young pendant
#

That

#
  1. before 2. after
hollow agate
#

Hm

young pendant
#

info command is from 119 - 143

hollow agate
#

I would recommend to fetch it straight out of the database?

young pendant
#

the weird thing is, I have a /add_role command for the rollen

#

Both times, the role twitch mod is being display properly

hollow agate
#

Okay, welp just do this in the info command

#

role_id = (905095402448101406,)
a = int(role_id[0])

#

Just convert the role_id to an int with [0] to forcefully remove the tuple

#

I lied, do this @young pendant

#
try:
    a = int(role_id[0])
except:
    a = int(role_id)```
#

If it's not a tuple, what I sent previously would've failed

#

I know it's not the best/most correct solution, but it does work

young pendant
#

Where do I put it exactly? @hollow agate

hollow agate
#

Erm

#
    async def info(self, guild_id):
        embed = discord.Embed(title="Info", color=discord.Colour.from_rgb(64, 118, 227))
        try:
            a = int(self.team_roles[guild_id])[0])
        except:
            a = int(self.team_roles[guild_id])
        if self.roles_of_team[guild_id] != [] and guild_id in self.team_roles.keys():
            val = ""
            for x in self.roles_of_team[guild_id]:
                val = val + f"<@&{x}>\n"
            embed.add_field(name="Teamrolle:", value=f"<@&{a}>", inline=False)
            embed.add_field(name="Rollen:", value=val)
            return embed
        elif self.roles_of_team[guild_id] != []:
            val = ""
            for x in self.roles_of_team[guild_id]:
                val = val + f"<@&{x}>\n"
                print(x)
            embed.add_field(name="Teamrolle:", value="keine Rolle festgelegt", inline=False)
            embed.add_field(name="Rollen:", value=val)
            return embed
        elif guild_id in self.team_roles.keys():
            print("just teamrole")
            embed.add_field(name="Teamrolle:", value=f"<@&{a}>", inline=False)
            embed.add_field(name="Rollen:", value="keine Rollen festgelegt")
            return embed
        else:
            embed.add_field(name="Error", value="Es sind keine Rollen für diesen Server festgelegt.")
            return embed```
#

I think that should work

#

I didn't try to understand what's going on in the code, but that's the gist

young pendant
#

SyntaxError: unmatched ')'

hollow agate
#

Whoops

#

do a = int(self.team_roles[guild_id][0])

#

Sorry about that 😅

young pendant
#

you are a legend my guy

#

Thanks so much

hollow agate
#

Did it work?

young pendant
#

Yeah, the only issue I have is that the bot needs to assign the role TEAMto a user automaticly if the user has the role Twitch Mod the bot does not do this right now but the info command works fine

young pendant
#

Its a bot for Category roles
Team is a category and the twitch mod is a normal role

#

if user has twitch mod, give him team role

slate swan
#
@bot.command()
async def mute(ctx, member:discord.User = None, reason = None, *, time):
  time = humanfriendly.parse_timespan(time)
  if reason is None:
    await ctx.send("Please write the reason!")
    return
  if time is None:
    await ctx.send("Please mention the time like 1d 1h 1m!")
    return
  if member is None:
    await ctx.send("Please mention the member you want to mute")
    return
  if member == ctx.message.author:
    await ctx.send("You cant mute yourself!")
    return  
  await member.edit(timed_out_until=discord.utils.utcnow()+datetime.timedelta(seconds=time))
  await ctx.send(f"{member.mention} קיבל מיוט\n סיבה: {reason}")```
```discord.ext.commands.errors.MissingRequiredArgument: time is a required argument that is missing.```
but if i do that time = None so it cant be cuz time is an int so what do i do
hollow agate
#

Can you explain why you can’t time=None?

slate swan
#

discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: expected string or bytes-like object

young pendant
#

@hollow agate thanks again, I'll get some sleep now cough 6:30 am here cough

young pendant
#

Have a good one

hollow agate
#

You too!

hollow agate
#

The code will fail if you don’t have that check at the top of the command

slate swan
#

i did if time is None

hollow agate
#

That works too

slate swan
#

it didnt work

hollow agate
#

Send the code

slate swan
#
@bot.command()
async def mute(ctx, member:discord.User = None, reason = None, *, time = None):
  time = humanfriendly.parse_timespan(time)
  if time is None:
    await ctx.send("Please put the time!")
  if reason is None:
    await ctx.send("Please write the reason!")
    return
  if time is None:
    await ctx.send("Please mention the time like 1d 1h 1m!")
    return
  if member is None:
    await ctx.send("Please mention the member you want to mute")
    return
  if member == ctx.message.author:
    await ctx.send("You cant mute yourself!")
    return  
  await member.edit(timed_out_until=discord.utils.utcnow()+datetime.timedelta(seconds=time))
  await ctx.send(f"{member.mention} קיבל מיוט\n סיבה: {reason}")```
#

discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: expected string or bytes-like object

hollow agate
#

Put time is None above the time = thing

slate swan
#

what

hollow agate
#

& you have two if time is None:

slate swan
#

time = None

#

yes

hollow agate
#
@bot.command()
async def mute(ctx, member:discord.User = None, reason = None, *, time = None):
  if time is None:
    await ctx.send("Please put the time!")
   return
  time = humanfriendly.parse_timespan(time)
  if reason is None:
    await ctx.send("Please write the reason!")
    return
  if member is None:
    await ctx.send("Please mention the member you want to mute")
    return
  if member == ctx.message.author:
    await ctx.send("You cant mute yourself!")
    return  
  await member.edit(timed_out_until=discord.utils.utcnow()+datetime.timedelta(seconds=time))
  await ctx.send(f"{member.mention} קיבל מיוט\n סיבה: {reason}")```
#

Copy that and it’ll work

slate swan
#

okay i will try

#

works!

#

tysm

hollow agate
#

You’re welcome :)

slate swan
#

discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'User' object has no attribute 'edit'
@hollow agate

#

when im trying to mute

#

which is weird

hollow agate
#

Do member: discord.Member = None

#

instead of member = discord.User = None

slate swan
#

oh okay

hollow agate
#

User is for global things like getting their ID or whatever

#

Member is for server things like timing them out or editing their roles

slate swan
#

ohh

#

works!

#

tysm!

hollow agate
#

You're welcome :)

glad cradle
slate swan
#

pls someone help me

upbeat otter
upbeat otter
slate swan
upbeat otter
#

hm

slate swan
#

what does the error code mean

upbeat otter
#

you must have atleast 5 options to fulfil the max-values parameter

#

but in your case you have commented out the other 4

slate swan
upbeat otter
#

yes

slate swan
#

alr i will try

slate swan
#

any fix to this?

slate swan
slate swan
slate swan
slate swan
#

@slate swan sent you the code in dms

slate swan
upbeat otter
upbeat otter
slate swan
#

@slate swan any fix to it ?

slate swan
slate swan
slate swan
#

The bot uses slash commands

#

i tried doing it and it showed so

#

it has many commands in the main.py but it can't be run

#

CommandNotFound is raised when a prefix command does not exists

#

unless you're using some stinky fork

#

in config.yaml , the prefix is $

#

and that's what I used

upbeat otter
slate swan
#

i used a slash commands , it didn't worked , then i used a $ command

slate swan
#

still it didn't work

#

line 64

slate swan
#

it responded nothing

slate swan
upbeat otter
slate swan
# slate swan i dont see anything wrong

well that file does not exist, and your interpreter wont lie
it seems like a logic issue from your side
check if the file exists or not, if it doesnt, make your code do that

slate swan
slate swan
slate swan
upbeat otter
#

😔 sad to know

slate swan
#

not only boost , it's happening with every command , al the code of the bot is located in the file I sent you

slate swan
#

is your bot even running?

slate swan
upbeat otter
slate swan
slate swan
lucid latch
#
async def play(ctx: interactions.CommandContext, query: str):
    queue = []
    if not discord.VoiceClient.is_connected():
        await discord.connect()```what's wrong?
#

module 'discord' has no attribute 'connect'

slate swan
#

i think you mean to use <some_channel>.connect

upbeat otter
slate swan
slate swan
slate swan
#

you gotta type / wait for a menu to popup

#

and select boost from there

upbeat otter
unkempt canyonBOT
#

await connect(*, timeout=60.0, reconnect=True, cls=<class 'discord.voice_client.VoiceClient'>, self_deaf=False, self_mute=False)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Connects to voice and creates a [`VoiceClient`](https://discordpy.readthedocs.io/en/latest/api.html#discord.VoiceClient "discord.VoiceClient") to establish your connection to the voice server.

This requires [`voice_states`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.voice_states "discord.Intents.voice_states").
slate swan
upbeat otter
#

oh wait that's py-cord

slate swan
#

more like cursedcord

slate swan
upbeat otter
#

but....but....py-cord is love 😭

slate swan
#

the menu isn't popping up

upbeat otter
#

right, I'll be off, will complete my episode :pepecry:

slate swan
#

once it pops up , ig il be able to run all commands

slate swan
#

yeah thats the issue

#

use the actual discord mobile client

#

ok

#

il be in the actual discord mobile Cline tin a min

slate swan
upbeat otter
# lucid latch ah.. can u tell me eg?
@bot.command(...)
async def foo(ctx: ...):
  if not ctx.voice_client.is_connected():
    channel = bot.get_channel(channel_id) or await bot.fetch_channel(channel_id)
    await channel.connect()
upbeat otter
slate swan
#

average CBSE student

upbeat otter
#

💀

lucid latch
#

i'll try them!

upbeat otter
#

,

slate swan
#

yo thanks for the help it worked! @slate swan

#

great, np

lucid latch
#
import discord
import interactions
bot = interactions.Client("mybottoken")```
#

discord-buttons-plugin 0.1.2
discord.py 2.0.1
discord-py-interactions 4.3.4
pycord 0.1.1

lucid latch
#
  if not ctx.voice_client.is_connected():
        channel = bot.get_channel(channel_id) or await bot.fetch_channel(channel_id)```
naive briar
#

Then what's the error

crimson horizon
#

How can I check if the bot gets kicked/banned in a guild?

slate swan
#

you can just know if your bot was removed, not if it was kicked or banned

crimson horizon
#

Okay, no problem

#

how do I do that?

slate swan
#

!d discord.on_guild_remove this event

unkempt canyonBOT
#

discord.on_guild_remove(guild)```
Called when a [`Guild`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild "discord.Guild") is removed from the [`Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client").

This happens through, but not limited to, these circumstances...
crimson horizon
#

okay thanks

mighty pilot
#

Does the bot have to be in a voice channel to see others connect and disconnect from it?

slate swan
#

no

silk fulcrum
#

uhm, so what would I use?
units = pdt.pdt_locales['en_US'].units? I'm not sure that will work

slate swan
#

isnt the library documented?

silk fulcrum
#

but i have no idea what the heck that is

#

and how to read that

slate swan
#

loooli after seeing this i can gladly say i make good documentation

vocal snow
slate swan
#

is what you need mb

#

the heck is this tho?

silk fulcrum
#

had to dig a lil bit

silk fulcrum
#

and docs say this

#

("source code" link)

#

maybe it's just me dumb

#

no idea how that works

slate swan
#

what is this library meant to do?

silk fulcrum
#

I just use it's Calendar

#

and locales (regret it now)

slate swan
#

pep8 loves this library

silk fulcrum
slate swan
#

the class naming <3

#

anyways, im out of ideas

silk fulcrum
#

ok im outta here

slate swan
silk fulcrum
#

idk why, but this reminds me Pascal

#

PascalABC editor (iirc)

slate swan
#

wow wtf

silk fulcrum
#

there is literally nothing in the __init__.py file of this lib (version, author & license), I might want to rewrite it myself, or it's just going to be a torture lol

silk fulcrum
slate swan
#

i love this library, 11/10

#

im getting this error again 😭

silk fulcrum
slate swan
silk fulcrum
#

ill just edit this shit

#

if it's even possible...

slate swan
#

good luck with that

silk fulcrum
#

i mean what on earth is rfc822

#

it's not on pypi

#

not in any of my files on my PC

#

but only in it

#

how does RoboDanny use this shit

slate swan
#

wtf

silk fulcrum
#

i just chose it because RoboDanny used it

#

and it worked

#

until today, when I switched back to windows

#

maybe that is the problem

#

Windows 10 = shit?

#

bruh, my song in the bg: "You made me a psycho, a psycho"

#

@slate swan i found a secret way

vocal snow
#

monkeypatching ?

silk fulcrum
pliant gulch
silk fulcrum
slate swan
slate swan
#

whatever used that library

pliant gulch
#

What are you even trying to do?

silk fulcrum
silk fulcrum
#

in commands like giveaway for example

slate swan
unkempt canyonBOT
slate swan
#

!pip time-str

unkempt canyonBOT
slate swan
#

consider these

silk fulcrum
#

ok, thx

#

I will do that later, I'm too tired

#

actually im not tired I just wanna play my sweet Portal 2

alpine cove
#

!d datetime.datetime.strftime

unkempt canyonBOT
#

datetime.strftime(format)```
Return a string representing the date and time, controlled by an explicit format string. For a complete list of formatting directives, see [strftime() and strptime() Behavior](https://docs.python.org/3/library/datetime.html#strftime-strptime-behavior).
alpine cove
#

!d datetime.datetime.strptime

unkempt canyonBOT
#

classmethod datetime.strptime(date_string, format)```
Return a [`datetime`](https://docs.python.org/3/library/datetime.html#datetime.datetime "datetime.datetime") corresponding to *date\_string*, parsed according to *format*.

This is equivalent to:

```py
datetime(*(time.strptime(date_string, format)[0:6]))
```  [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError "ValueError") is raised if the date\_string and format can’t be parsed by [`time.strptime()`](https://docs.python.org/3/library/time.html#time.strptime "time.strptime") or if it returns a value which isn’t a time tuple. For a complete list of formatting directives, see [strftime() and strptime() Behavior](https://docs.python.org/3/library/datetime.html#strftime-strptime-behavior).
alpine cove
#

*one

pliant gulch
#

Because this doesn't use human readable rather a C standard format

pliant gulch
#

%m %H %I is human readable?

#

Heres an example from parsedatetime ```py
result = p.parse("tomorrow")

parseDate() is a helper function that bypasses all of the

natural language stuff and just tries to parse basic dates

but using the locale information

result = p.parseDate("4/4/80")

parseDateText() is a helper function that tries to parse

long-form dates using the locale information

result = p.parseDateText("March 5th, 1980")

#

These are obviously human readable, where as strptime isn't

#

@silk fulcrum Are you doing py from parsedatetime import pdtLocales or ```py
import parsedatetime

pliant gulch
#

Try the first one I showed

silk fulcrum
pliant gulch
#

Alright

alpine cove
silk fulcrum
#

thanks for trying to help

silk fulcrum
pliant gulch
alpine cove
silk fulcrum
pliant gulch
#

Binary is too long so unless you want have a very large book length wise hexidecimal would be better

#

They both can do about the same thing anyways

#

I'd much rather prefer to work with hexidecimal rather than binary to store data when programming as well

slate swan
#

make your own new computing system

alpine cove
#

I recently just read:
00110000 00100000 01100110 01100001 01100011 01110100 01110011 00100000 01100001 01100010 01101111 01110101 01110100 00100000 01100001 01101110 01101001 01101101 01100001 01101100 01110011

#

it roughly translated to:
110000 facts about animals

slate swan
#

the fact that you wasted more bytes in sending that message than how much they actually are

#
class Giveaway(commands.Bot):

    def __init__(self, bot):
      self.bot = bot
    
    @bot.command()
    @commands.has_permissions(manage_channels = True)
    async def create(self, ctx, mins: int, *, prize: str):

      embed=discord.Embed(title="New Giveaway!")
      embed.add_field(name="Prize", value=f"{prize}")
      end=datetime.datetime.utcnow() + datetime.timedelta(seconds=mins*60)
      embed.add_field(name="Ends At", value=f"{end}UTC")
      embed.set_footer(text=f"Ends {mins} min from now!")

      my_msg = await ctx.send(embed=embed)

      await my_msg.add_reaction("🎉")

      await asyncio.sleep(mins*60)

      new_msg = await ctx.channel.fetch_message(my_msg.id)

      users = await new_msg.reaction[0].users().flatten()
      users.pop(users.index(bot.user))

      winner = random.choice(users)


      embed2 = discord.Embed(title="Winner!", description=f"{winner.mention}")
      embed2.set_thumbnail(url=winner.avatar_url)
      embed2.add_field(name="Prize", value=f"{prize}")
      embed2.set_footer(text="Giveaway Ended!")

      server = ctx.message.guild

      await ctx.send(f"{winner.mention}", embed=embed2)
      await winner.send(f"You won the giveaway in {server.name} !")```


```discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: create() missing 1 required positional argument: 'mins'
#

and i did mins]

#

the

#

discord.ext.commands.errors.BadArgument: Converting to "int" failed for parameter "mins".

#

heck is this

#

what

#

giveaway system

#

why are you passing a bot instance to a Bot object?

vale wing
#

the

spice scroll
#

my intents are still not working no matter what i do

#

!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. By default discord.py has all intents enabled except for Members, Message Content, and Presences. These are needed for features such as on_member events, to get access to message content, and to get members' statuses.

To enable one of these intents, you need to first go to the Discord developer portal, then to the bot page of your bot's application. Scroll down to the Privileged Gateway Intents section, then enable the intents that you need.

Next, in your bot 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

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

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

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

mighty pilot
mighty pilot
#

And does the bot have proper permission in the server

spice scroll
#

what intents have to be specified?

mighty pilot
#

Whatever it needs for your situation

naive briar
#

Depends on what you need

drifting cypress
#

hello , how to create an ephemeral message ? i tried

@bot.command()
async def message_invisible(ctx):
    print("running")
    await ctx.
send("Text", ephemeral=True)

but it doesn't work :/ it displays running but that's it

naive briar
#

Only for interaction commands

#

Like slash command / message command

mighty pilot
#

Slash commands are better anyways imo

glad cradle
mighty pilot
#

Like autocorrect for your bot lol

spice scroll
drifting cypress
mighty pilot
# unkempt canyon

Read the docs link at the bottom here it should help you understand intents

glad cradle
glad cradle
#

what library are you using

drifting cypress
vale wing
#

When the

vale wing
mighty pilot
#

Rip

vale wing
#

Use pip freeze and see

vale wing
#

What version of dpy

drifting cypress
vale wing
#

Nah I need concrete

#

Some people say "latest" but turns out they are on 1.7

spice scroll
#

ok so

vale wing
#

Do pip show discord.py @drifting cypress

spice scroll
#
TypeError: __init__() missing 1 required keyword-only argument: 'intents'

not sure what intent i need

vale wing
#

!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. By default discord.py has all intents enabled except for Members, Message Content, and Presences. These are needed for features such as on_member events, to get access to message content, and to get members' statuses.

To enable one of these intents, you need to first go to the Discord developer portal, then to the bot page of your bot's application. Scroll down to the Privileged Gateway Intents section, then enable the intents that you need.

Next, in your bot 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

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

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

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

drifting cypress
vale wing
glad cradle
#

wth 20.0.2

vale wing
#

Ikr

#

Me when the

naive briar
#

He's from the future

glad cradle
#

try to do print(discord.__version__)

spice scroll
#

-_-

#

did that already joe_8bit

drifting cypress
glad cradle
jagged adder
#

if im trying to print a list of all users in my server, how do i exclude all bots ?
not just the bot in which im executing the cmd

glad cradle
jagged adder
#

ik its something simple, but idr the right wording

drifting cypress
spice scroll
glad cradle
vale wing
jagged adder
#
id_list = '\n'.join([f' - **{m.name}** *({m.id})*' for m in ctx.guild.members if m != ...])
glad cradle
spice scroll
#

and it says im missing intents from an __init__()

jagged adder
#

whats the correct ending to that...

spice scroll
#

k

naive briar
vale wing
spice scroll
#
import discord
from discord import Intents
from discord.ext import commands


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

client = discord.Client()
client = commands.Bot(command_prefix=">", intents=intents)

@client.event
async def on_ready():
    print("{0.user} is online!".format(client))
jagged adder
#

to print a list of all ids and names of users in the text channel

#

i alrdy got it working, im just trying to filter bots

vale wing
naive briar
vale wing
spice scroll
#

💀

jagged adder
#

ah...

drifting cypress
#

Done , so now i can use interactions ? how do i do so ?

spice scroll
#

alr got rid of the top one

jagged adder
#

cheers, nice easy fix for once lol

spice scroll
#

still bugged because a bot that worked perfectly fine a year ago has to be broken as hell now

vale wing
#

Because everything get updated

spice scroll
#

0.0

vale wing
#

Downgrade dpy and it will work fine, but many features will be unsupported

glad cradle
#

guys I use disnake so I can't help you more than that with slash commands, pithink

spice scroll
#

well yeah but ive been struggling with my limited knowledge of python and very limited brain power to get this thing online

vale wing
#

Extend it and it'll be easier for you to understand all this and get help

#

If dpy 1.7 was relatively ok for beginners, 2.0 is totally not beginner-friendly

spice scroll
#

hellnah

glad cradle
#

If you are looking to work with interactions in my opinion the most beginner friendly library is Disnake

vale wing
#

Agreed

slate swan
spice scroll
#

hmm

#

if only quitting was an option 😂

vale wing
#

🦶

glad cradle
#

it's still on alpha

slate swan
#

its a VVIP package

spice scroll
#

oh

slate swan
#

talking about slash commands
gimme some slash command implementation ideas for my wrapper pe

glad cradle
#

is it a discord api wrapper?

slate swan
#

yeah

vale wing
#

You need sync methods or event processing or smth (slash commands are done through gateway right?)

slate swan
#

slash commands can work thru both gateway and rest ( because they are part of the interactions )

#

you recieve a "INTERACTION_CREATE" payload if you're using gateway

mighty pilot
#

Imo 2.0 makes more sense than 1.7 but I also wasn't making bots in 1.7

vale wing
#

Ah yes that's what I thought

slate swan
#

im talking about the command constructor tho, like discord.py implemented CommandTrees which people dont seem to prefer

mighty pilot
#

What don't people like about command trees?

vale wing
#

Personally I would just put them all together, fetch list of current commands, compare them and sync ones that were updated

slate swan
#

one reason for that can be it gives better control

spice scroll
slate swan
#

but again, disnake provides full control with the basic bot class only too

mighty pilot
#

Yea kinda but I prefer redundant lmao. From the little bit of disnake api that I've looked at it looks more user friendly on the code side

hushed galleon
#

i think the major benefit of the command tree is code decoupling from the client, but of course lib users dont care about that

drifting cypress
#
async def message_invisible(ctx):
    print("running")
    await interaction.response.send("Text", ephemeral=True)

still not working with / prefix :/

slate swan
#

ephemeral responses can be created only for interactions

mighty pilot
slate swan
#

you dont even have interaction defined there

mighty pilot
#

There's some changes you need to make to convert it to a slash command

drifting cypress
vale wing
#

🤓

vale wing
#

and videos

drifting cypress
#

i googled it and it says discord.py does not support slash commands

mighty pilot
#

There's some helpful resources. it's a handful of things you need to change

vale wing
#

Outdated

mighty pilot
vale wing
glad cradle
#

I was going to send it

mighty pilot
#

If I seperate my stuff out into cogs, I'm assuming anything that uses a view needs that view to be in the same cog right?

slate swan
#

thats upto you, personally i keep things that do same kind of thing in single cog independent of the features they use

mighty pilot
#

So I could have my views in one cog and the command that uses them in another without troubles?

hushed galleon
#

in theory yes, but you should take care when referencing things from other extensions, particularly making sure they're loaded

#

if you dont think you'll need to hot-reload your view classes, you can put them in a regular module (.py) and import it in your extension

mighty pilot
#

I was planning to put everything into regular modules and import them into the main file, so I should also import them into the other cogs that will use pieces of it is what you're saying

hushed galleon
#

yeah thats fine

mighty pilot
#

Alright. Wish me luck lol I'm sure everything is going to go exactly as planned pikawut5

spice scroll
#

ayo disnake worked

upbeat otter
#

it is certainly supposed to, why wouldn't it 💀

spice scroll
upbeat otter
spice scroll
#

couldnt figure out intents

slate swan
#

could have asked here, or just used !intents loooli

upbeat otter
#

more like disnake has the same class for intents 💀

#

intents in both the libraries are accessed in the same way

#

¯_(ツ)_/¯

spice scroll
#

disnake seems to be easier for beginners/low skilled programmers (me lol) and more akin to the older version of discord.py i used to use

slate swan
spice scroll
#

as my bot gets more complex i'll prolly move back over but for now this is fine

hushed galleon
#

tbf the point of requiring intents= is precisely to inform you of its existence

slate swan
#

disnake is just a fork anyways

upbeat otter
#

right

slate swan
#

loooli and breaking bad tutorials, so you bot never runs until you apply your brain

upbeat otter
hushed galleon
#

does disnake have a warning for starting a commands.Bot without message_content?

spice scroll
#

a.doesnt require intents
b. worked for my bot

slate swan
slate swan
hushed galleon
unkempt canyonBOT
#

disnake/ext/commands/bot_base.py lines 154 to 162

warnings.warn(
    "Message Content intent is not enabled and a prefix is configured. "
    "This may cause limited functionality for prefix commands. "
    "If you want prefix commands, pass an intents object with message_content set to True. "
    f"If you don't need any prefix functionality, consider using {alternative}. "
    "Alternatively, set prefix to disnake.ext.commands.when_mentioned to silence this warning.",
    MessageContentPrefixWarning,
    stacklevel=2,
)```
upbeat otter
#

who suggested that after all

slate swan
upbeat otter
#

ew

slate swan
#

just like discord[voice] works

slate swan
unkempt canyonBOT
slate swan
#

installs this package alongside

upbeat otter
#

cursed

slate swan
spice scroll
#

rip

#

discord2? dang

primal token
#

the sequel

slate swan
#

thats just pycord under the hood

upbeat otter
upbeat otter
slate swan
spice scroll
#

weird

upbeat otter
slate swan
upbeat otter
slate swan
paper sluice
#

self.bot

slate swan
#
@bot.command()
@commands.has_permissions(ban_members=True)
async def ban(ctx, member:discord.Member=None,*,reason=None):
  if not member:
    await ctx.reply("בבקשה תתייג מישהו!")
    return
  if member.top_role >= ctx.author.top_role:
    embed3=discord.Embed(color=discord.Colour.red(), 
    title="Ban System", description="למשתמש יש גישות מעלייך, לא אפשרי לתת לו באן!")
    await ctx.reply(embed=embed3)
    return
  await member.ban(reason=reason)
  await ctx.reply(embed=discord.Embed(title=f"{member.name} קיבל באן \n איש צוות: {ctx.author.name}", description=f"סיבה: **{reason}**"))
@ban.error
async def ban_error(ctx, error):
  if isinstance(error, commands.CheckFailure):
    await ctx.reply("אין לך גישה לתת באן..")```

and if someone that his role is higher then me trying to ban me it says error
```discord.ext.commands.errors.CommandInvokeError: Command raised an exception: Forbidden: 403 Forbidden (error code: 50013): Missing Permissions
#

like how do i do that if the bot has perm then the bot can ban not the member

slate swan
slate swan
#

i wanna do that if the bot has perm to ban then it will not the member

wicked atlas
#

Check that the bot has the permission in your sever settings, and that the bot has a role higher than the member you are trying to ban

slate swan
#

like

wicked atlas
#

I think the role hierarchy affects it

slate swan
#

listen

#

u understood me wrong

wicked atlas
#

Ah, I see, I just skimmed your message and read the error

slate swan
#

when i am trying to ban someone that his role is biggeer then mine it sent but if his role higher then my it shows the error

wicked atlas
#

Then his role is probably higher than the bot's

slate swan
#

u didnt understand

#

yes his role is higher then the bot but so do mine

wicked atlas
#

yeah I didn't

slate swan
#

and when someone that his role higher then me AND higher then the bot so it shows that error

slate swan
wicked atlas
#

You could add checking for that missing permissions error in your handler

@ban.error
async def ban_error(ctx, error):
  if isinstance(error, commands.CheckFailure):
    await ctx.reply("אין לך גישה לתת באן..")
  elif isinstance(error, commands.MissingPermissions):
    await ctx.reply("no perms")
slate swan
#

oh thanks

#

Bro took it personally

alpine cove
#

indeed

#

u should be using d.py anyways

wicked atlas
#

¯_(ツ)_/¯

alpine cove
#

(╯°□°)╯︵ ┻━┻

slate swan
alpine cove
slate swan
alpine cove
#

bruh I just wanna go to your place and talk

slate swan
#

Anyway how far you squirt

hollow badger
#

Let's keep it civil and random personal questions are weird.

alpine cove
#

lol

hollow badger
slate swan
alpine cove
slate swan
hollow badger
#

This is a Discord bots channel. Please stay on topic.

slate swan
#

I live in Ohio

alpine cove
#

gotcha

#

see you in 2h

#

anyways discord bots

slate swan
#

Are overrated self bots >>>

alpine cove
#
from discord.ext import commands

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

@bot.command()
async def test(ctx):
    await ctx.message.reply("test")
bot.run("tol")
#

I hope that works

#

I'm on my phone rn so I cant check

drifting cypress
#
class SlashBot(commands.Bot):
    def __init__(self) -> None:
        super().__init__(command_prefix=".", intents=discord.Intents.default())

    async def setup_hook(self) -> None:
        self.tree.copy_global_to(guild=discord.Object(id=12345678900987654))
        await self.tree.sync()

bot2 = SlashBot()

@bot2.tree.command(name="ping", description="...")
async def _ping(interaction: discord.Interaction) -> None:
    await interaction.respond("pong",ephemeral=True)

When i use the ping command i have the following error :
discord.app_commands.errors.CommandNotFound: Application command 'ping' not found
but if i remove the "ephemeral" part it works , but i'm trying to get it to reply with an ephemeral message , anyone have a fix for that ?

upbeat marsh
#

Can anyone tell me how to get server list
Thru jishaku

slate swan
alpine cove
#

1h and 50m

#

soon...

#

very soon

wicked atlas
#

Looks like discord.py, but Interaction objects don't have respond methods

upbeat marsh
#

Can anyone tell me how to get server list
Thru jishaku

wicked atlas
#

don't know why you didn't get an error for that

drifting cypress
#

yep , still getting the same error

hushed galleon
spice scroll
#

ok umm i can't get discord.py/disnake on my laptop because it says I have to get VisualStudio 14.0. Do I have to?

#

it works on my PC

drifting cypress
upbeat marsh
#

Can anyone tell me how to get server list
Thru jishaku

hushed galleon
#

only one of those lines will work, since run() is a blocking method

drifting cypress
#

jeez

upbeat marsh
#

pusheen_ramen_noodles i want to know the jsk command
Which will return all the servers list in which my bot is

#

Jsk kinda new 4 me

hushed galleon
hushed galleon
drifting cypress
#

so there's no way i can have command (bot = commands.Bot(command_prefix=PREFIX, description='',intents=discord.Intents.all()) and slash (bot2 = SlashBot()) at the same time ?

hushed galleon
#

do you actually need both bots though?

#

or rather are you using the same token for bot and bot2?

drifting cypress
#

not really XD just trying to learn discord's API and trying to include as much as possible

hushed galleon
#

then you dont actually need bot2

drifting cypress
#

oki thx

upbeat marsh
#

jsk py
e = []
for guild in bot.guilds:
try:
if guild.owner.id not in e:
e.append(guild.owner.id)
except:
pass
await ctx.send(f'{len(e)}/{len(bot.guilds)}')

#

This is my cmd in jsk but the bot wont reply

#
e = []
for guild in bot.guilds:
  try:
    if guild.owner.id not in e:
      e.append(guild.owner.id)
  except:
    pass
await ctx.send(f'{len(e)}/{len(bot.guilds)}')```
hushed galleon
#

did you include your bot's prefix in front of jsk?

#

and jishaku specifically provides the _bot variable, the leading underscore is necessary

upbeat marsh
#

Ohh k

slate swan
#

@cedar smelt i just saw your bio, im trying to use flask with vue, can you help me?

upbeat marsh
# alpine cove use filters
jsk py
e = []
for guild in bot.guilds:
  try:
    if guild.owner.id not in e:
      e.append(guild.owner.id)
  except:
    pass
await ctx.send(f'{len(e)}/{len(bot.guilds)}')```
slate swan
upbeat marsh
#

@slate swan hmm

#

That's what i want to check

slate swan
#
len(set([guild.owner_id for guild in _bot.guilds]))
#

run this in jishaku

#

ty!

grave grove
#

How can i check if a role already exists on a server, and if it exists the bot moves it on top of all the other existing roles and add it to the user who used the command

slate swan
#

!d discord.Guild.roles check if the role is in the list

unkempt canyonBOT
#

property roles```
Returns a sequence of the guild’s roles in hierarchy order.

The first element of this sequence will be the lowest role in the hierarchy.
slate swan
#

and if it exists the bot moves it on top of all the other existing roles and add it to the user who used the command
bot can move roles only till its top role, not above that

slate swan
#

yo

#

some guy told me its better to use / prefix

#

instead of "!", is that true ? for a discord bot

naive briar
#

Slash commands have extra features that text commands don't

#

Like autocompletes or ephemeral response

keen dust
primal token
slate swan
#

Hello!

I am making a discord bot with cogs:

Code:

class Owner(commands.Cog):
    def __init__(self, bot):
        self.bot = commands.Bot = bot

    times = datetime.now()
    embedcolor = 0xf47fff

    def owner(ctx):
        perms = json.load(open('modules/assets/config/perms.json'))
        return str(ctx.author.id) in perms["OWNER_ID"]

    @commands.slash_command(description="Gives a target staff")
    async def givestaff(self, ctx, target:discord.Option(discord.Member, "Who am I making staff?")):
        if not owner(ctx):
            embed=discord.Embed(title="Insufficient perms", description="It seems you don't have permissions to use this command", color=embedcolor, timestamp=times)
            await ctx.respond(embed=embed, ephemeral=True)
        else:
            pass

But if not owner(ctx) + embedcolor + times

Is error saying it is not defined... How would I fix that?

sick birch
slate swan
slate swan
sick birch
#
class Owner(commands.Cog):
  def __init__(...) -> None:
    ...
  def is_owner(self, ctx: commands.Context) -> bool:
    ...

  @commands.slash_command(...)
  async def givestaff(self, ...) -> None:
    is_owner = self.is_owner(...)
#

for instance

#

(this was meant for @slate swan )

indigo pilot
#

Hey quick question

guess this is kinda like a command but, im doing a on message event and need to check if the message is something like "simon says change your status to {online/dnd/etc}. How do i

  1. do the check for the multiple statues of online, dnd, etc
  2. check what one they choose

i could just do a bunch of elif status to online, etc but itheres prob a btter way

slate swan
#

also by any chance is it possible to prevent my code from creating a __pycache__ folder when I run my bot?

sick birch
#
status = text.split(" ")[-1]
keen dust
slate swan
#

hey!

I have a command

perms["STAFF_ID"].append(......)

How would I make a command that removes there id from that .json file?

slate swan
#
async def unban(ctx, *, member):
    banned_users = ctx.guild.bans()
    member_name, member_discriminator = member.split('#')
    
    for ban_entry in banned_users:
        user = ban_entry.user

        if(user.name, user.discriminator) == (member_name, member_discriminator):
            await ctx.guild.unban(user)
            await ctx.channel.send(f"Unbanned: {user.mention}")
#

im getting an error in this code

#

File "c:\Users\foodi\Desktop\DiscordBot_Files\discord_bot.py", line 63, in unban
for ban_entry in banned_users:
TypeError: 'async_generator' object is not iterable

#

why?

shrewd apex
keen dust
keen dust
#

tired, now I'll head out

#

addios

shrewd apex
#

bai bai

slate swan
#
@bot.tree.command(name="clear", description="Clears number of messages")
@commands.has_permissions(manage_messages=True)
@app_commands.describe(amount = "Please put an amount to clear")
async def clear(interaction: discord.Interaction, amount : int):
    await interaction.channel.purge(limit=amount)
    await interaction.response.send_message(f"{amount} messages cleared.")```


```discord.app_commands.errors.CommandInvokeError: Command 'clear' raised an exception: NotFound: 404 Not Found (error code: 10062): Unknown interaction

#

what do i do instead of interaction.channel.purge then

naive briar
#

Your interaction took too long to respond

slate swan
#

what do i do w that

#

how can i change it

naive briar
#

Defer the interaction and respond with a followup

#

!d discord.InteractionResponse.defer

unkempt canyonBOT
#

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

Defers the interaction response.

This is typically used when the interaction is acknowledged and a secondary action will be done later.

This is only supported with the following interaction types...
slate swan
#

interaction.response.send_message instead of that

#

like it is clearing the messages

#

but not showing the message

indigo pilot
slate swan
unkempt canyonBOT
#

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

(x)
naive briar
#

Is it just me not understanding questions or it's that hard to understand

slate swan
#

use the -1nth index

indigo pilot
#

!e ```py
sentence = "Simon says set your custom status to this won’t work"
print(sentence.split()[-1])

unkempt canyonBOT
#

@indigo pilot :white_check_mark: Your 3.11 eval job has completed with return code 0.

work
indigo pilot
#

lol

slate swan
#

!e

print("hi")
#

!e

class Questions(commands.Cog):
	def __init__(self, bot: commands.Bot):
		self.bot = bot
		
    @commands.Cog.listener()
    async def on_ready(self):
    	print('Soru yüklendi')
		
	@commands.command()
	async def sync(self, ctx) -> None:
		fmt = await ctx.bot.tree.sync(guild=ctx.guild)
		await ctx.send(f'Synced {len(fmt)} commands.')
		
	@app_commands_command(name="Daneme", description="soru sor oruspu")
	async def questions(self, interaction: discord.Interaction, question: str):
		await interaction.response.send_message('Sonunda başardın 2 gündür dc.Py eğitimi alıyorsun cahilsin')

async def setup(bot):
	await bot.add_cog(Questions(bot), guilds=[discord.Object(id=1023275954388336660)])
velvet compass
lament depotBOT
#

Here are the top 5 results:

Sending a normal message after a slash command is run
Upload file to slash command - discord.py
How to add reaction in discord.py slash command
How do I import a slash command from a different file with discord.py?
How do i make a working slash command in discord.py
slate swan
#

how do i make a slash command be avilable only to a perm

#
@app_commands.has_permissions(manage_messages=True)``` ?
grand willow
slate swan
#

Hi

#

yo

indigo pilot
naive briar
#

Sarth answered that question

indigo pilot
slate swan
#
@bot.command()
@commands.has_permissions(ban_members = True)
async def ban(ctx, member: discord.Member, *, reason = None):
    await member.ban(reason=reason)
    ban = discord.Embed(title=f":hammer: Banned {member.name}!", description=f"Reason: {reason}\nBy:{ctx.author.mention}")
    await ctx.message.delete()
    await ctx.channel.send(embed=ban)
    await member.send(embed=ban)
#

im writing this code rn but im only able to ban someone by mentioning them. how can i make it so that there are multiple ways to ban them, whether by mentioning them, writing down their name, or copying their discord ID?
here is the code.

#
@app_commands.has_permissions(manage_messages=True)``` ? for slash commands?
grand willow
#

Are u getting any errors while trying to do it with the id?

indigo pilot
slate swan
indigo pilot
slate swan
naive briar
#

I said you took too long to respond

indigo pilot
#

^

grand willow
grand willow
unkempt canyonBOT
#

get_member_named(name, /)```
Returns the first member found that matches the name provided.

The name can have an optional discriminator argument, e.g. “Jake#0001” or “Jake” will both do the lookup. However the former will give a more precise result. Note that the discriminator must have all 4 digits for this to work.

If a nickname is passed, then it is looked up via the nickname. Note however, that a nickname + discriminator combo will not lookup the nickname but rather the username + discriminator combo due to nickname + discriminator not being unique.

If no member is found, `None` is returned.

Changed in version 2.0: `name` parameter is now positional-only.
indigo pilot
#

whats the thing to wait again, async.wait(5)? i forget

grand willow
indigo pilot
#

it handles that for u

indigo pilot
slate swan
#
  File "C:\Users\dynam\Documents\predictor\main.py", line 20, in <module>
    tree = app_commands.CommandTree(client)
  File "C:\Users\dynam\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\app_commands\tree.py", line 134, in __init__
    raise ClientException('This client already has an associated command tree.')
discord.errors.ClientException: This client already has an associated command tree.
PS C:\Users\dynam\Documents\predictor>```
indigo pilot
#

yo quick one more question, how do i check a members status and custom status?

slate swan
unkempt canyonBOT
#

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

this won’t work
slate swan
#

like

slate swan
unkempt canyonBOT
#

property status```
The member’s overall status. If the value is unknown, then it will be a [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)") instead.
slate swan
#

!d discord.Member.activities for playing , custom activities etc

unkempt canyonBOT
#

The activities that the user is currently doing.

Note

Due to a Discord API limitation, a user’s Spotify activity may not appear if they are listening to a song with a title longer than 128 characters. See GH-1738 for more information.

indigo pilot
#

ah ty

naive briar
#

The bot already has a tree

slate swan
indigo pilot
slate swan
#

yes

indigo pilot
#

ah thanks

slate swan
slate swan
#

client.tree.command then

#

error?

#

edited.

slate swan
#

you gotta sync your commands too

#

!d discord.app_commands.CommandTree.sync

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

im like practicing coding

indigo pilot
#

ah

slate swan
#

yea

slate swan
slate swan
#

bot.tree.sync

grand willow
unkempt canyonBOT
#

get_member(user_id, /)```
Returns a member with the given ID.

Changed in version 2.0: `user_id` parameter is now positional-only.
grand willow
slate swan
indigo pilot
#

!e
user = bot.get_user(986703977313865838)
user.activities

unkempt canyonBOT
#

@indigo pilot :x: Your 3.11 eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 1, in <module>
003 | NameError: name 'bot' is not defined
indigo pilot
#

ok i dont know how this bots eval works just ognna ask lmao

indigo pilot
#

since its all activiies, for playing, watching, etc im not sure

steel void
#

I have a column in a database table that is type json, would it be better to use Postgres's built in functions for making changes to the json or importing the json object to python and making my changes there?

slate swan
unkempt canyonBOT
#

class discord.Activity(**kwargs)```
Represents an activity in Discord.

This could be an activity such as streaming, playing, listening or watching.

For memory optimisation purposes, some activities are offered in slimmed down versions:

• [`Game`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Game "discord.Game")

• [`Streaming`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Streaming "discord.Streaming")
indigo pilot
#

what if it isnt a game th o? a normal users discord status isnt anything

slate swan
#

its a custom activity object then

indigo pilot
#

!jsk py
guild =_bot.get_guild(811284392156725339)
a = guild.get_member(842859032628822057)
abc = a.activities
abc.name

#

oops

slate swan
#
@commands.has_permissions(ban_members = True)
async def ban(ctx, member: discord.Member, *, reason = None):
    await member.ban(reason=reason)
    ban = discord.Embed(title=f":hammer: Banned {member.name}!", description=f"Reason: {reason}\nBy:{ctx.author.mention}")
    await ctx.message.delete()
    await ctx.channel.send(embed=ban)
    await member.send(embed=ban)
slate swan
#

it just doesnt bruh

#

i have to mention them it doesnt ban if i type their name

grand willow
#

what are the erros

slate swan
#

discord.ext.commands.errors.MemberNotFound: Member "chillman" not found.

#

but if i tag them like @hard seal

naive briar
#

You should use a converter if you're using discord.py

slate swan
grand willow
slate swan
naive briar
#

Forget about what I have said

slate swan
#

but i want it so that it bans by name

grand willow
naive briar
#

It can accidentally ban someone with the same name

slate swan
slate swan
grand willow
#

i would help u but i gtg

slate swan
spice solstice
#

hey, if I want to upload text to a free online source like pastebin and then be able to edit it with a python script. any suggestions for what I could use?

slate swan
#

does the pastebin have an API?

spice solstice
#

only delete/create

slate swan
#

well then you can read the pastebin first, then create a new one with edited content Shrug thats all you can do

spice solstice
slate swan
#

well then use a pastebin that allows you to edit the content lol

spice solstice
#

im trying to send a discord inv created from a bot to a twitch overlay.
I thought the best way would be to upload the inv to a text host and just add that as a browser source for the stream

sick birch
#

I think you're looking for a database, no?

#

Or at least a storage service like AWS S3

spice solstice
#

its literally a single line of text though 🥲

sick birch
#

Why not store it locally then

slate swan
#

use a gist

spice solstice
sick birch
#

"stream"?

spice solstice
#

twitch stream overlay

spice solstice
slate swan
#

whenever i use
\033[39m when i open the program it just does ←[39m

#

Does anyone know a fix to this?

fading marlin
#

the unicode for ansi is \u001b

slate swan
glad cradle
#

is it a bad idea to use os.stat on File to get file size?
is it a heavy blocking call?

fading marlin
fading marlin
slate swan
#

the text

#

I have a print statement

#

print("\033[39mRunning")

#

but thats what is shows

fading marlin
#

oh, then use the colorama module

slate swan
#

i dont wanna use colorama

#

thats the thing

fading marlin
#

then you'll have to use the escape character (\u001b) to get the ansi formatting

slate swan
#

so how would i use it?

#

in the print statement

fading marlin
#

it's unicode, you literally just copy and paste that to the left of the opening bracket

slate swan
#

doesnt work.

slate swan
fading marlin
#

fwiw 39 won't get you anything either

slate swan
#

it gives white

fading marlin
#

it's 40-47 for background, and 30-37 for foreground

slate swan
#

i want it too look like that but just a print statement

#

and only white

fading marlin