#discord-bots

1 messages · Page 79 of 1

heady citrus
#

I asked how would i make it case insensitive

slate swan
#

this code totally fails lmao,
what if the message has 2 items from the words list in it
you can't delete the same.message twice

winged coral
primal token
unkempt canyonBOT
#

@primal token :white_check_mark: Your 3.11 eval job has completed with return code 0.

Yes >:(
naive briar
#

I don't understand what you're saying

simple kettle
#

where do i put the check, do i put it in the command and check to see if the value still equals the default value?

wintry panther
#

nvm found out

primal token
#
if not value:
    ...
simple kettle
primal token
#

try it and see!

#

are the filtered words all lowercased?

dark pine
#

why this one gives me an error

#
        if isinstance("MissingAnyRole", (commands.MissingRole, commands.MissingAnyRole)):
            await ctx.send("you dont have the role")
primal token
#

?

heady citrus
slate swan
#

also, this will never be true, why are you comparing a string with those objects in instance

dark pine
#

im trying to except the missinganyrole error

#

to send a reply message

slate swan
#

how was i not clear with the python version thing, that will work only and only in python 3.10+

#

are you on that version?

slate swan
#

what is wrong with this code?

#

whenever I print the event content it just puts "none" in the terminal

sick birch
primal token
#

Its probably an intent issue

sick birch
#

MTAxNzQ3MjE50TQyNDIyOTQz0A.GpjYj1.0oq9w7GgZNhR8Xj2vWn_UmwAn2MRw9IM2N4rH8

#

hopefully it resets it automatically

slate swan
#

its a test boty

ionic garden
#

why are the return types different?

wicked atlas
#

because calling fetch_member will return a coroutine, which then needs to be awaited

primal token
ionic garden
#

ok god
thanks

primal token
wicked atlas
#

literally the exact same wording but ok

primal token
#

No?

sick birch
#

It Returns a coroutine upon the calling of the function

because calling fetch_member will return a coroutine

slate swan
#

what are intents

wicked atlas
slate swan
#

and where do I put it

wicked atlas
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.

slate swan
#

ah thanks!

slate swan
#

whats wrong with this?

wicked atlas
#

but what is wrong with it?

ionic garden
#

so uh i'm getting a 403 even though the bot has admin perms in my server and intents is Intents.all()?

wicked atlas
ionic garden
#

discord.errors.Forbidden: 403 Forbidden (error code: 50013): Missing Permissions
pretty standard stuff

wicked atlas
#

What line is it happening on in the traceback?

slate swan
slate swan
ionic garden
#
    role = discord.utils.get(server.roles, name="test")
    member = await server.fetch_member(user.id)
    print(dir(member))
    await member.add_roles(role)
```the 4th one
sick birch
#

you

wicked atlas
slate swan
#

OH FUCK I DIDNT SEE THAT

primal token
# slate swan whats wrong with this?

Dont leak any part of your token, especially the most important part, Your run method is inside of a function and youre missing the message content intent and use if member is None:

wicked atlas
ionic garden
primal token
slate swan
wicked atlas
primal token
ionic garden
wicked atlas
#

since that looks like replit, I would definitely suggesting using secrets

primal token
#

Does secrets have cryptography? Not exactly sure why you recommended it

wicked atlas
slate swan
#

I wanted to see if it was just a visual stud problem

#

wtf does this mean

wicked atlas
#

more intents stuff!!!!

#

make sure you've enabled the intents you need in the dev portal

slate swan
#

...

wicked atlas
slate swan
#

oh it worked

#

I havent coded discord.py in like 3 years I didnt know what intents were 💀

wicked atlas
#

yeah, the kwarg just became required with 2.0

primal token
#

?

ionic garden
#

still doesn't work?

wicked atlas
#

Is it still the same 403 error?

ionic garden
#

yeah

wicked atlas
#

try going into role settings and explicitly enabling the manage roles permission

dull terrace
#

if you create a class instance and put it in a dictionary dict["something"] = class(values) and then make a reference to it reference = dict["something"] and then do del dict["something"] are you also deleting reference

wicked atlas
wintry panther
#

how do i make the bot detect who used the slash command

primal token
wicked atlas
naive briar
#

!d discord.Interaction.user

unkempt canyonBOT
wintry panther
wintry panther
#

!d

unkempt canyonBOT
dull terrace
#

!e

class banana:
  def __init__(self, bob):
    self.bob = bob

butt = {}
butt["something"] = banana("test")
jeff = butt["something"]
del butt["something"]

try:
  print(jeff)
except:
  print("no longer exists")
unkempt canyonBOT
#

@dull terrace :white_check_mark: Your 3.11 eval job has completed with return code 0.

<__main__.banana object at 0x7fd60b8af950>
wintry panther
steel pier
#
channel = embed=discord.Embed(title="Logs Messages", description=f"Message de {message.author} {message.content}")
await message.channel.send(embed=embed)
channel = client.get_channel(1017579623552405554)```
Hi, I would like the {message.author} not to be repeated (it's for a "Logs Messages" discord room
wicked atlas
wintry panther
#

oh ok

wicked atlas
#

if you just did pip install discord, you're probably using discord.py

wintry panther
#

nvm

#

why does this happen when i use keepalive

primal token
wintry panther
wicked atlas
wintry panther
dull terrace
slate swan
#

commands not working

primal token
wicked atlas
# wintry panther why so

replits run on shared machines. So your bot is running on a computer that is shared with other people's replits, which might also be running discord bots, on a shared IP address. So if too many requests come from that computer, or someone decides to abuse the api or ratelimits from a replit that just happens to be on that machine, it'll get blocked, which blocks every replit running on that computer.

slate swan
#

@wicked atlas do you know the problem here?

naive briar
primal token
wicked atlas
wintry panther
naive briar
#

Mb

steel pier
#
channel = embed=discord.Embed(title="Logs Messages", description=f"Message de {message.author} {message.content}")
await message.channel.send(embed=embed)
channel = client.get_channel(1017579623552405554)```
Hi, I would like the {message.author} not to be repeated (it's for a "Logs Messages" discord room, HELP ME PLEASE.
slate swan
wicked atlas
slate swan
#

oops

#

wait

#

is that it or no

naive briar
#

I don't understand

primal token
wicked atlas
steel pier
wicked atlas
wintry panther
slate swan
wintry panther
wicked atlas
#

especially since heroku just announced the end of their free plan

wicked atlas
dull terrace
#

it's not that expensive to buy hosting

slate swan
dull terrace
#

like half of the price of an amazon subscription

primal token
wintry panther
#

also what do theese do

slate swan
#

im dumb srry

slate swan
#

I think

wicked atlas
wintry panther
naive briar
primal token
wintry panther
#

what does WARNING: This is a development server. Do not use it in a production deployment. this mean

slate swan
#

Python discord bot

wicked atlas
steel pier
# naive briar Can you show the full code for that
async def on_message(self, message): 
    channel = embed=discord.Embed(title="Logs Messages", description=f"Message de {message.author} {message.content}")
    await message.channel.send(embed=embed)
    channel = client.get_channel(1017579623552405554)```
wintry panther
steel pier
wicked atlas
wintry panther
#

So it will stillwrokpriperly?

wicked atlas
#

still, wouldn't suggest using replit as a hosting service, at least the free tier

naive briar
# steel pier Uh yes ?....

So, you're trying to log the message by sending the embed to the channel where the message was sent, and the message that your bot sent will also be logged, and it keeps looping

steel pier
wicked atlas
#

Then let's fix that

if message.author == client.user:
    return
steel pier
naive briar
# steel pier ?

You can put that on top of the log function to check if the message author is your bot or not. If it is, then don't log it

steel pier
naive briar
# steel pier I want the bot messages to be ignored

Then just add the check to it

async def on_message(self, message):
    if message.author.id == bot.user.id:
        return

    embed = discord.Embed(title="Logs Messages", description=f"Message de {message.author} {message.content}")
    await message.channel.send(embed=embed)
    channel = client.get_channel(1017579623552405554)```
naive briar
#

Ah

#

Is your function in a cog?

steel pier
#

Error in the "bot" level 👀

wicked atlas
steel pier
naive briar
#

So no

naive briar
#

Are you subclassing the bot? Like

class MyBot(Bot):
    ...
dark pine
#

hosting a bot online 3$ is the cheapest option?

naive briar
#

Right

dark pine
#

thats not cheap 😄

naive briar
# steel pier no class MyClient

You can simply replace bot with self

async def on_message(self, message):
    if message.author.id == self.user.id:
        return

    embed = discord.Embed(title="Logs Messages", description=f"Message de {message.author} {message.content}")
    await message.channel.send(embed=embed)
    channel = client.get_channel(1017579623552405554)```
dark pine
naive briar
#

Nah nah

dark pine
#

oh

#

so there is any cheaper prices to run a bot online?

#

is there any free one?

wicked atlas
#

either there is some kind of catch, or you're the product

full lily
jagged adder
#

is it possible to make a function that runs upon finishing watching a linked video? im tryin to do something for my sisters bday in a couple days, and want to create a special interactive experience through my bot. If not, i’m prob going to just have a time delay just over the length of the vid and hope it lines up approximately

#

perhaps some kind of timer that starts once someone interacts with the vid ?

slate swan
jagged adder
#

as it’s almost certainly going to exceed discords 8MB max file upload, prob dropbox

slate swan
#

I see

wicked atlas
jagged adder
#

i don’t recall the formats that standard videos are in either

wicked atlas
#

I think it's still possible to modify video lengths to look infinite, if you want to make them watch the whole thing 😈

jagged adder
slate swan
#

there's no point in adding a button either 'cause no, I don't think that's possible because you'll never when a client clicked a button/clicked on any link etc.

jagged adder
#

yup

#

also how would i set a timer that goes off at a set epoch time?

#

ie 12pm local time

#

so not a timeout, but something that’ll go off at x time

#

id presumably need some kind of bot.event that uses the epoch time as a trigger

wicked atlas
#

I would use a task that checks the time every second or so, then once the expected time is reached, send the message then end the task

slate swan
#

and it'll run whenever the time matches the current time

jagged adder
#

ah

wicked atlas
#

ooo, never noticed that

slate swan
#

same lmao

jagged adder
jagged adder
#

ah

slate swan
#

there's no involving of events

wicked atlas
#

you might want to stop the task when it runs. The docs say "The exact times to run this loop at", so it might run more than once.

jagged adder
#

ah ok

jagged adder
wicked atlas
#

with a datetime object

jagged adder
#

or id still need a decorator above

#

ok so date/time differs from epoch how

#

i mean how does it convert to local

wicked atlas
#

datetime is apython module, and it's expecting a datetime.time object

jagged adder
#

so the format of that would just require some googling i spose

#

alright

wicked atlas
#

I think you could do something like this

from datetime import datetime
from discord.ext import tasks

@tasks.loop(time=datetime.utcfromtimestamp(1662684959))
async def my_task() -> None:
  ...

my_task.start()
bot.run()
jagged adder
#

couldn’t u just import datetime 👀

#

or is it some kind of weird same-name stacking it has going on

wicked atlas
#

!d datetime.datetime

unkempt canyonBOT
#

class datetime.datetime(year, month, day, hour=0, minute=0, second=0, microsecond=0, tzinfo=None, *, fold=0)```
The *year*, *month* and *day* arguments are required. *tzinfo* may be `None`, or an instance of a [`tzinfo`](https://docs.python.org/3/library/datetime.html#datetime.tzinfo "datetime.tzinfo") subclass. The remaining arguments must be integers in the following ranges...
jagged adder
#

alright

jagged adder
wicked atlas
#

check what?

jagged adder
#

wait stupid me im doubling up; the datetime alrdy does what a check would be doing

#

my bad

#

it’s a task on a loop right, will it just loop infinitely until the datetime matches what it’s set to?

#

most python things check really quick, what stops the task from spamming time checks constantly

wicked atlas
#

No, it'll run it only at the specified times

#

idk what it does to check the time, but I can look

jagged adder
#

o

patent lark
#

👋

jagged adder
#

ello snow

patent lark
#

hello.

wicked atlas
#

You know what it probably does, it gets the current time and figures out how much time is between the time it starts and the time it should run, then sleeps the task for that long

jagged adder
#

i’ll have to do some digging later; at the moment im mostly afk tbh

jagged adder
#

could be

wicked atlas
#

that's what it looks like at a glance under the hood

jagged adder
#

fair

#

well i appreciate the help y’all! i gtg but i’ll lyk how it goes when i get to it

wicked atlas
#

👍

sick birch
#

yo

#

That's an excellent question to ask your interpreter

steel pier
#
async def on_member_join(member, role): 
    role = discord.utils.get(member.guild.roles, id="1016124782980366338")
    await member.add_roles(member, role)```
Hey, I would like when a member joins my server to add a specific role, can you help me?
rare echo
#

you get the member when they join and you add_roles to member

primal token
steel pier
#
channel = client.get_channel(1017227196303151255)
await channel.send(f"Bienvenue a {member.mention} sur le serveur !")```
How could I place an embed on this?
rare echo
#

:|

#

!d discord.Embed

primal token
#

!d discord.Embed

unkempt canyonBOT
#

class discord.Embed(*, colour=None, color=None, title=None, type='rich', url=None, description=None, timestamp=None)```
Represents a Discord embed.

len(x) Returns the total size of the embed. Useful for checking if it’s within the 6000 character limit.

bool(b) Returns whether the embed has any data set.

New in version 2.0.

x == y Checks if two embeds are equal.

New in version 2.0...
steel pier
#

I know how to make an embed, but I don't know how to place it there @rare echo

rare echo
#

channel.send(embed=embedname)?

primal token
#

Ghost ping

rare echo
#

decided to ping you for it

primal token
#

The process of streaming music in a discord bot is mainly impossible or quite hard especially with a platform's TOS and mainly licensing issues

rare echo
#

oh i’m aware

primal token
#

Just saying it in general

crimson plover
#

so im trying to color this text am i missing something here?

#

this seems to do nothing as well

naive briar
crimson plover
#

Is there something dumb im missing when trying to color or highlight the background of said text such as help within the embed

#

trying to do something similar to this

naive briar
#

Slash command mentions?

crimson plover
#

is that how?.. was trying to stay away from the slash commands but if thats the only way

#

i guess i didnt even think of that

naive briar
#

What?

steel pier
# naive briar What?
if message.content.lower().startswith('+ticket'):
   await message.delete()
   await message.guild.create_text_channel(f'Ticket {message.author}')
steel pier
vale wing
#

What exactly does it say

steel pier
vale wing
#

What does the warning say

steel pier
vale wing
#

You just had the correct version in your code

#

For some reason you edited it and removed the kwarg

#

!d discord.Guild.create_text_channel

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...
steel pier
#

@vale wing

await create_text_channel(name, *, reason=None, category=None, news=False, position=..., topic=..., slowmode_delay=..., nsfw=..., overwrites=..., default_auto_archive_duration=...)```
Should I use this?
vale wing
#

You mean in how many servers is the user banned in? You can count only ones that the bot is in

vale wing
#

You need overwrites kwarg

#

Check example in documentation

steel pier
vale wing
#

There's only one isn't there

steel pier
vale wing
#

Then why you asked lol

steel pier
vale wing
#

That's a big issue

#

I personally don't recommend using d.py if you don't have enough knowledge

#

You won't last long only with copypasta

steel pier
steel pier
vale wing
#

You need to provide a dict to overwrites kwarg where everyone role and member object are keys and instances of discord.PermissionOverwrite are values

vale wing
fresh marsh
#

can anyone help me with post method

vale wing
#

To what endpoint

fresh marsh
vale wing
#

And uh what kind of help do you need

fresh marsh
#

its just thinking

fresh marsh
vale wing
#

Could you show your code

fresh marsh
#

dms? or here

vale wing
#

Here

fresh marsh
#
@commands.has_role(requiredRoleId)
async def ban_user(ctx, userid: str):   
    await ctx.defer(ephemeral=True)
    conn = http.client.HTTPSConnection(websiteUrl)
    headers = {"Content-type": "application/json"}
    conn.request("POST", BanPath, json.dumps({"userid": userid}), headers)
    content = json.loads(conn.getresponse().read().decode("utf-8-sig"))
    if json["data"]:
         await ctx.respond("\nUsername: %s | > Successfully Unbanned" % (ctx.author.id, content["data"]))
    else:
         await ctx.respond(content["data"])```
vale wing
#

Your code is just blocking

fresh marsh
#

response it

vale wing
#

Use aiohttp for requests

vale wing
#

!pypi aiohttp

unkempt canyonBOT
fresh marsh
#

websiteUrl = "" -- website link
BanPath = "" --endpoint

vale wing
#

Did you read what I said

fresh marsh
#

oh wait mb

jagged adder
#

do on.message events cancel out commands? coz yday when i created an on.message bot.event to listen for something containing the bots name and then reply, it caused every one of my bot.command funcs to stop functioning at all

#

didn’t matter where in the code it was, above or below the commands i was trying to call

#

it’s like the on_message event overrode them; is that typical? and if so, how would i be able to have both commands and events?
i know i wasn’t using a check=, which may be part of the issue

naive briar
#

!d discord.ext.commands.Bot.process_commands

unkempt canyonBOT
#

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

This function processes the commands that have been registered to the bot and other groups. Without this coroutine, none of the commands will be triggered.

By default, this coroutine is called inside the [`on_message()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_message "discord.on_message") event. If you choose to override the [`on_message()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_message "discord.on_message") event, then you should invoke this coroutine as well.

This is built using other low level tools, and is equivalent to a call to [`get_context()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.get_context "discord.ext.commands.Bot.get_context") followed by a call to [`invoke()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.invoke "discord.ext.commands.Bot.invoke").

This also checks if the message’s author is a bot and doesn’t call [`get_context()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.get_context "discord.ext.commands.Bot.get_context") or [`invoke()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.invoke "discord.ext.commands.Bot.invoke") if so.

Changed in version 2.0: `message` parameter is now positional-only.
still iris
#

So I got this command to resolve usernames from userid, how do I make it accept multiple userids instead of just one? Ex; getuser "firstID" "secondID" "thirdID"

async def getuser(ctx, id: int):
    user = await bot.fetch_user(id)
    print(user)```
tidal hawk
#
@bot.command()
async def getusers(ctx, *, ids):
  for userid in ids.split(' '):
    if userid.isdigit(): user = await bot.fetch_user(int(user))

Example: !getusers user1 user2 user3

#

@still iris

#

Maybe you can skip the isdigit part with type annotation

vocal snow
#

you can just ```py

@bot.command()
async def getusers(ctx, *ids: int):
...

#

or use the UserConverter

#

but that only does a cache lookup

#

why are you doing this?

#

isn't msg already a Message object

#

why are you fetching the message again, just call delete on msg

#

although that error looks a bit like a bug, what version of discord.py are you on

jagged adder
dark pine
#

Anyone knows a free vps go run discord bot in?

fresh marsh
#
@bot.slash_command(name="unban", description="test")
@commands.has_role(requiredRoleId)
async def ban_user(ctx, userid: str):
    await ctx.defer(ephemeral=True)
    conn = http.client.HTTPSConnection(websiteUrl)
    headers = {"Content-type": "application/json"}
    conn.request("POST", BanPath, json.dumps({"userid": userid}), headers)
    content = json.loads(conn.getresponse().read().decode("utf-8-sig"))
    print(content)
    if json["data"]:
        await ctx.respond("<@%s>, Successfully banned %s.")
    elif json["errors"]:
        await ctx.respond(json["errors"])
    else:
        await ctx.respond("<@%s>, Failed to ban %s. Please try again")```
how to make this request via body
naive briar
#

Uh

#

Why are you trying to get data from json lib?

fresh marsh
#
@bot.slash_command(name="unban", description="test")
@commands.has_role(requiredRoleId)
async def ban_user(ctx, userid: str):
    await ctx.defer(ephemeral=True)
    conn = http.client.HTTPSConnection(websiteUrl)
    headers = {"Content-type": "application/json"}
    conn.request("POST", BanPath, json.dumps({"userid": userid}), headers)
    content = json.loads(conn.getresponse().read().decode("utf-8-sig"))
    print(content)
    if content["data"]:
        await ctx.respond("<@%s>, Successfully banned %s.")
    elif content["errors"]:
        await ctx.respond(json["errors"])
    else:
        await ctx.respond("<@%s>, Failed to ban %s. Please try again")
naive briar
#

What problem are you having with this command?

fresh marsh
#

not via json dump and idk how to do it

#

request to my website with body

naive briar
#

Why don't you use aiohttp or requests for the HTTP requests?

fresh marsh
fresh marsh
#

i'm new to this kind of stuff

naive briar
#

I honestly don't know

boreal ravine
rugged shadow
fresh marsh
#

but you can ban people by discord bot

#

roblox blocked direct connections to discord

vale wing
#

@fresh marsh I already told you to use aiohttp, there are examples on their pypi page

#

And in their docs client quickstart

vale wing
vale wing
#

Amazon AWS - free for 1 year
Microsoft Azure - free for 1 year + some services free forever, not sure which ones exactly
Oracle - to my knowledge free forever but they sell your data or smth, you heard the news about lawsuit

fresh marsh
#

i mean the aio thing im gonna try tho ty

vale wing
fresh marsh
vale wing
#

Ok

#

You better figure aiohttp out, it's much easier than the thing you are using right now

slate swan
#

Hello, SO when i want to download PIP so i can import the modules its showing this Python was not found; run without arguments to install from the Microsoft Store, or disable this shortc, even though, i have PYTHON installed.

paper sluice
still iris
tidal hawk
#

Add it then

radiant parrot
#

How would I add a length to the mute? ```py
@client.command()
async def mute(ctx, user: discord.Member, reason):
guild = ctx.guild
mutedRole = discord.utils.get(guild.roles, name="Muted")

if not mutedRole:
    mutedRole = await guild.create_role(name="Muted")

    for channel in guild.channels:
        await channel.set_permissions(mutedRole, speak=False, send_messages=False)

await user.add_roles(mutedRole, reason=reason)
await send_mute(user, 'my fancy reason', ctx)```
maiden fable
#

await asyncio.sleep

jagged adder
#

why does this ```py
switch = ['off']
@bot.command(name='killswitch')
async def delswitch(ctx, switch):
if ctx.author.id in [..., ...]:
if 'on' in switch:
switch.clear()
switch.append('off')
ctx.channel.send("Killswitch activated.")
elif 'off' in switch:
switch.clear()
switch.count('on')
ctx.channel.send("Killswitch deactivated.")

come up with this error

discord.ext.commands.errors.MissingRequiredArgument: switch is a required argument that is missing.

vale wing
merry cliff
#

when yo urun the comand, did you include the switch?

vale wing
merry cliff
#

e.g. !killswitch on

vale wing
#

Or just use timeout

radiant parrot
vale wing
vale wing
radiant parrot
vale wing
#

I have an example with temp ban lemme fetch it for you rq

merry cliff
radiant parrot
vale wing
#

No need

jagged adder
#

ah got it working now

radiant parrot
merry cliff
#

ok

jagged adder
#

cheers

vale wing
unkempt canyonBOT
#

ext/system.py lines 78 to 91

@tasks.loop(minutes=30)
async def bans_remover(self):
    await self.bot.wait_until_ready()
    now = datetime.now()
    records = await self.bot.db.execute(
        "SELECT * FROM bans WHERE unban_at < $1", now, fetch_mode=FetchMode.ALL
    )
    for r in records:
        try:
            await self.bot.server.unban(disnake.Object(r["id"]))
        except disnake.HTTPException:
            await self.bot.log.warning("Failed to unban %s", r["id"])

    await self.bot.db.execute("DELETE FROM bans WHERE unban_at < $1", now)```
vale wing
#

You just need to understand the principle

#

What the hell is wrong with this code

#

Why is log.warning awaited

#

What was I on

radiant parrot
#

So is that checking the db every 30 mins?

vale wing
#

Yeah

radiant parrot
#

How have u created ur db? Like what kinda code

#

As i have used dbs before but not for discord bot

vale wing
#

In most of my projects I use postgres

#

Including this one

#

Good thing about it is that it supports time storage

rigid narwhal
#

hello, is there a way to remove all role perms from a channel? basically a reset

vale wing
#

In sqlite you'd have to store timestamps as integers

unkempt canyonBOT
#

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

Edits the channel.

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

Changed in version 1.3: The `overwrites` keyword-only parameter was added.

Changed in version 1.4: The `type` keyword-only parameter was added.

Changed in version 2.0: Edits are no longer in-place, the newly edited channel is returned instead...
vale wing
#

I am not absolutely sure but I think you just need to provide empty dict to overwrites kwarg

#

!d discord.TextChannel.set_permissions

rigid narwhal
#

couldn't find anything regarding resetting perms

unkempt canyonBOT
#

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

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

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

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

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

You must have the [`manage_roles`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_roles "discord.Permissions.manage_roles") permission to use this...
shrewd apex
radiant parrot
vale wing
rigid narwhal
#

yep thanks

vale wing
#

You need to provide None to overwrite kwarg

vale wing
vale wing
radiant parrot
shrewd apex
radiant parrot
vale wing
#
unmute_time = datetime.now() + timedelta(days=1)
await execute("INSERT INTO unmutes (id, unmute_timestamp) VALUES (?, ?)", (user.id, unmute_time.timestamp()))```
Some pseudocode for you
#

why not simply use discord timeout

naive briar
#

Excellent question

radiant parrot
#

Then take the role away

placid skiff
#

Bruh just use timeout D_D

#

!d discord.Member.timeout

unkempt canyonBOT
#

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

Applies a time out to a member until the specified date time or for the given [`datetime.timedelta`](https://docs.python.org/3/library/datetime.html#datetime.timedelta "(in Python v3.10)").

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

This raises the same exceptions as [`edit()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member.edit "discord.Member.edit").
rigid narwhal
# unkempt canyon

this didn't work for me, i have several channels with different role perms, i just want to make all channels public again

placid skiff
#

then iterate through all that channels and remove all those perms D_D

rigid narwhal
#

yeah how to remove all pems

#

tried overrides didn't work out

#

i can go through all roles but thats totally not efficient

#

almost 200 roles

placid skiff
#

well if that's that bad as you say you have to remove all roles D_D

rigid narwhal
vale wing
radiant parrot
#

How would i use the discord.member.Timeout? Any have example thanks

rugged shadow
#

read the docs

#

!d discord.Member.timeout

unkempt canyonBOT
#

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

Applies a time out to a member until the specified date time or for the given [`datetime.timedelta`](https://docs.python.org/3/library/datetime.html#datetime.timedelta "(in Python v3.10)").

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

This raises the same exceptions as [`edit()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member.edit "discord.Member.edit").
radiant parrot
#

im still bit confused

naive briar
# radiant parrot im still bit confused

So, you basically just give it the time that you want the timeout to be put out

from datetime import datetime, timedelta
...
date = datetime.utcnow() + timedelta(minutes=30)
await member.timeout(date)
naive briar
radiant parrot
#

is tht the only bit of code u need for timingout?

naive briar
#

Pretty much

radiant parrot
#

Ahh

naive briar
#

Or you can just use timedelta

await member.timeout(timedelta(minutes = 30))
radiant parrot
#

Thank you v much

#

How would fix this error? py await send_mute(message.author, f'Suggesting non-needed post for {channel_sent_in}') TypeError: send_mute() missing 1 required positional argument: 'ctx'

#
async def send_mute(user, reason: str, ctx):
    em = discord.Embed(title="**MUTED**", description=f"{user} was muted because: {reason}",
                       color=discord.Color.red())
    em2 = discord.Embed(title="**MUTED**", description=f"You have been mute because: {reason}",
                        color=discord.Color.red())
    await user.send(embed=em)
    await user.send(embed=em2)

@client.command()
@has_permissions(manage_channels=True)
async def mute(ctx, member: discord.Member):
    date = datetime.utcnow() + timedelta(minutes=1440)
    await member.timeout(date)```
naive briar
#

You can just remove ctx from it if you don't need it

async def send_mute(user, reason: str):
    em = discord.Embed(title="**MUTED**", description=f"{user} was muted because: {reason}",
                       color=discord.Color.red())
    em2 = discord.Embed(title="**MUTED**", description=f"You have been mute because: {reason}",
                        color=discord.Color.red())
    await user.send(embed=em)
    await user.send(embed=em2)
radiant parrot
#

ah yes, sorry became blind for a sec haha

vale wing
unkempt canyonBOT
#

class datetime.timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)```
All arguments are optional and default to `0`. Arguments may be integers or floats, and may be positive or negative.

Only *days*, *seconds* and *microseconds* are stored internally. Arguments are converted to those units...
stone rune
#

discord.player: ffmpeg process 68 successfully terminated with return code of -11.

primal token
vale wing
#

Then it's __init__iater

primal token
#

ok

errant night
#

i want to implement the abilities from pokemon in my pokemon bot so the only way to do it is by making like a million if statements? 😭

silk fulcrum
errant night
#

i wrote like 3 and gave up instantly

silk fulcrum
#

what are you trying to do?

#

how do those ifs look like?

shell wing
#

eh i forgot how to install dpy2..what was the link and all ?

errant night
# silk fulcrum how do those ifs look like?

its like there is a battle system and within the system i have added a bunch of IF statements to make the abilties work like for venusaur's overgrow if the health gets below 30% its attacks will get a 50% boost

shell wing
#

wont it just install the v1 ?

#

dam i should check the notifs 😭

#

ty

rugged shadow
#

don't forget -U

#

to upgrade, if they have existing dpy 1x

#

pip install -U discord.py

primal token
iron sorrel
primal token
#

your __all__ dunder should be a tuple, why specify the subclassing of `object and why is their string concatenation when you could just use f-strings

iron sorrel
#

that is true! thanks for the feedback, what do you mean by most annotations?

#

also the mfa token string concat made more sense than putting that random generation in an fstring

primal token
iron sorrel
#

f"mfa.{random.choices(a + 'b' + c + 'd')}"

iron sorrel
primal token
#

Or you can just make a new instance of a string with all those values and then pass it to random.choices

#

Either way its not really a big deal as its just micro optimization but we have f-strings we should take advantage of their speed and syntax sugar, no?

iron sorrel
#
def __str__(self) -> str:
    hmac_chars = string.digits + string.ascii_letters + "-" + "_"
    hmac = "".join(random.choices(hmac_chars, k=84))
    return f"mfa.{hmac}"
primal token
#

No need to make a variable(hmac) but sure

iron sorrel
#
def __init__(self, id: Optional[int] = None):
    self.id = id or Snowflake()
#

something about putting '' inside f"" is unsettling

primal token
iron sorrel
#

why does that need return annotations

primal token
#

Atleast be consistent with its usage

iron sorrel
#

how about this

paper sluice
#

you don't need to inherit from object

#

and sort your imports

iron sorrel
paper sluice
#

hmac_chars is a constant, so its better to initialize it in the class body instead of the function body

primal token
#
from typing import Optional
from typing import Tuple

you can just use a coma?

from typing import Optional, Tuple

And why the usage of Tuple, i'm pretty sure its been deprecated since 3.9 since tuple has parametization and why inherit from object and atleast use return annotation consistently

iron sorrel
#

well autoformatter splits that import into 2 lines

wicked atlas
#

Thats some weird formatter you got there

silk fulcrum
#

that is weird

primal token
#

Either way its useless to import Tuple

silk fulcrum
#

yeah, tuple exists

iron sorrel
#

i know, its not supported in 3.8 tho

paper sluice
iron sorrel
#

the same version which repl.it still uses for some odd reason but anyways

primal token
paper sluice
primal token
#

infact you shouldnt even need to use Optional

#

Just use pipes

paper sluice
#

I still like Optional

silk fulcrum
primal token
silk fulcrum
#

?

iron sorrel
#

yk what actually this is a silly python script for mocking snowflake and token generation

primal token
#

¯_(ツ)_/¯

iron sorrel
#

not a code written in rust to make rockets aim at tanks lmaoo

paper sluice
primal token
#

hes using __future__.annotations

#

It converts every annotation into a string so, yes.

iron sorrel
#

latest version with all the feedback

paper sluice
iron sorrel
#

and theyre not in __all__ so

paper sluice
#

oh, you are using it else where

iron sorrel
#

its used in Token and MfaToken

primal token
#

Then yeah youre good

paper sluice
#

👍 didnt notice

slate swan
#

can someone help me with my bot to make the command work only if it has member role for example tag me or dm pls

paper sluice
#

!d discord.ext.commands.has_role

unkempt canyonBOT
#

@discord.ext.commands.has_role(item)```
A [`check()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") that is added that checks if the member invoking the command has the role specified via the name or ID specified.

If a string is specified, you must give the exact name of the role, including caps and spelling.

If an integer is specified, you must give the exact snowflake ID of the role.

If the message is invoked in a private message context then the check will return `False`.

This check raises one of two special exceptions, [`MissingRole`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.MissingRole "discord.ext.commands.MissingRole") if the user is missing a role, or [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.NoPrivateMessage "discord.ext.commands.NoPrivateMessage") if it is used in a private message. Both inherit from [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure").

Changed in version 1.1: Raise [`MissingRole`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.MissingRole "discord.ext.commands.MissingRole") or [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.NoPrivateMessage "discord.ext.commands.NoPrivateMessage") instead of generic [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure")...
iron sorrel
slate swan
iron sorrel
#

this is not my code

vale wing
#

This is so sus code

primal token
#

str.format🙈

iron sorrel
#

its not MINE jkhfsjh

#
@commands.has_role() # role id, or role name
slate swan
primal token
#

Very precise i must say

iron sorrel
#

yeah

#

bruh it wont work like that you need to pass it the role name "as a string" or the role id as an int 12312312

slate swan
#

wdym with string

#

like that @commands.has_role("member")

primal token
#

it converts every annotation to a string

iron sorrel
#

that is not an annotation

primal token
#

Youre using it as a union

iron sorrel
#

!e

from __future__ import annotations

def foo(x: int | None):
  ...

print(foo.__annotations__)
unkempt canyonBOT
#

@iron sorrel :white_check_mark: Your 3.11 eval job has completed with return code 0.

{'x': 'int | None'}
iron sorrel
#

its a string here as you can see ^

#

!e

from __future__ import annotations

def foo(x: int | None):
  ...

assert isinstance(foo.__annotations__["x"], str)
unkempt canyonBOT
#

@iron sorrel :warning: Your 3.11 eval job has completed with return code 0.

[No output]
iron sorrel
#

yes, to support legacy py versions

primal token
#

Version safety? what

iron sorrel
primal token
#

I dont.

#

The term version safety makes no sense to me, enlightening me

iron sorrel
#

you cannot match case in 3.9 can you?

#

or def foo() -> list[int]:

silk fulcrum
iron sorrel
#

in 3.8

#

exactly

primal token
paper sluice
silk fulcrum
paper sluice
primal token
silk fulcrum
primal token
#

You mean match case trees?

silk fulcrum
#

trees 🗿

hushed galleon
paper sluice
# primal token I still dont understand

like, i have this 3.10 type annotation int | None, If I give to someone who is on 3.8, it will not work. But when i make the future import, it does. It is not the best Solution and if you trying to make your code compatible for older versions, you should certainly not do that, but this is one way.

silk fulcrum
#

wth

#

how does that relate to match case

primal token
#

Thats what i'm saying

#

I already know that, but how does that relate to match and case kek

iron sorrel
paper sluice
#

nope

primal token
#

What parametization?

iron sorrel
#

the thing is, python is not rust, future features are not compatible with past versions

silk fulcrum
iron sorrel
#

all the code written now, will be compatible with rust in the future but anyways so offtopic

hybrid seal
#

rust good 🚀

primal token
#

no

silk fulcrum
#

no

primal token
#

i like C++ better

silk fulcrum
#

oh yeah cpp is gud

hushed galleon
primal token
#

I personally like C++'s syntax better and its concepts over Rusts

paper sluice
#

!ot

unkempt canyonBOT
primal token
#

ok

silk fulcrum
#

why does it always send ot2 channel 🗿

night crater
#

because of channel activity

primal token
night crater
#

thats the point...

silk fulcrum
primal token
#

So it redirects you to a lonely channel so you talk to yourself

#

😔

silk fulcrum
#

yes :hahaa:

night crater
#

It redirects you to a channel to take the continue the conversation without disrupting an already existing conversation.

primal token
#

Im just joking around lol

silk fulcrum
primal token
#

.topic

lament depotBOT
#
**Do you think there's a way in which Discord could handle bots better?**

Suggest more topics here!

silk fulcrum
primal token
#

ok

silk fulcrum
#

ok

tidal hawk
#

lol

hybrid seal
#

idk maybe they should actually use API versions for breaking changes

primal token
night crater
#

Back in the good old days where Discord bots were a simple way to have fun and not a absolute nightmare of entitled users and forced rewrites

hybrid seal
#

at least they sorta fixed that with react on android

#

but now android discord is trash

primal token
#

It feels like i'm using WhatsApp in 2014

silk fulcrum
hybrid seal
hybrid seal
#

ex Locales didn't work on android until react native iirc

night crater
hybrid seal
#

yeah

night crater
#

And people still can't work out how to use slash commands!

silk fulcrum
hybrid seal
#

im not sure what its like outside of the hikari world, but at least for hikari theres not many questions about it.

silk fulcrum
night crater
hybrid seal
#

ok wth

#

never seen that lol

#

but im not surprised

primal token
hybrid seal
night crater
#

it's the reason why I tell people they don't want to make a big bot, at the start it's fun but then it just becomes a second job dealing with people not being able to read simple things at times. All the time.

hybrid seal
#

real

#

lib devs get it even worse cause they can't even take donations as easily

night crater
#

There's somewhat less user evolvement with lib dev

#

although I think Discord related library development is probably one of the easier things to do and get burnt out on

hybrid seal
#

yeah, i did get burned out from working on lib for about two months. Did come back to it though.

hollow ice
#

anyone help me??

How to send to user dm only slash cmd

@client.tree.command(name='hello', description='You test bot lmao')
async def hello(interaction: discord.Interaction):
  await interaction.response.send_message("Hello World")
tidal hawk
#

Ephemeral?

hollow ice
#

no

#

send to member dm without chat server

tidal hawk
#

So user can only use the command inside dm?

dull knot
#
    @commands.slash_command(name="hack", description="Hate someone? Hack their account!")
    async def HackUser(self, inter, target: disnake.Member):

        Message = await inter.send(f"Hacking {target}...")
        await asyncio.sleep(3)

        await inter.edit(f"1")
        await asyncio.sleep(2)

        await Message.edit(f"2")
        await asyncio.sleep(2)

When I did it with prefix cmds, it worked but with Slash_commands, it sends me the error:

"HackUser
    await inter.edit(f"1")
AttributeError: 'ApplicationCommandInteraction' object has no attribute 'edit'"

How do I fix this?

tidal hawk
#

inter.send -> inter.channel.send

dull knot
#

Ahhh, Nice. Thanks!

hollow ice
#

it worked :)

pulsar solstice
#

I made this rps bot

#
class rpsmenu(discord.ui.view):
    def __init__(self) -> None:
        super().__init__()
    embed=discord.Embed(title="RPS" ,description="Choose Your Move", colour=0x552E12)
    @discord.ui.button(label="Rock", style=discord.ButtonStyle.grey, emoji=":dsrock:")
    async def rock(button: discord.ui.Button, interaction:discord.Interaction):
        embedrps=discord.Embed(f"{randomrps}\n**Your move:** {interaction}")
        await interaction.response.send.send_message(embed=embedrps)
    @discord.ui.button(label="Paper", style=discord.ButtonStyle.grey, emoji=":paper:")
    async def paper(button: discord.ui.Button, interaction:discord.Interaction):
        embedrps=discord.Embed(f"{randomrps}\n**Your move:** {interaction}")
        await interaction.response.send.send_message(embed=embedrps)
    @discord.ui.button(label="Sissors", style=discord.ButtonStyle.grey, emoji=":sissors:")
    async def sissors(button: discord.ui.Button, interaction:discord.Interaction):
        embedrps=discord.Embed(f"{randomrps}\n**Your move:** {interaction}")
        await interaction.response.send.send_message(embed=embedrps)

@bot.command()
async def rps(ctx):
    view = rpsmenu()
    embed=discord.Embed(title="RPS" ,description="Choose Your Move", colour=0x552E12)
    await ctx.reply(embed=embed, view=view)

#

and now I am getting this error

#
  File "c:\Users\8ster\OneDrive\Desktop\projects\Discord Bots\Mighty Raju Bot\main.py", line 68, in <module>
    class rpsmenu(discord.ui.view):
TypeError: module() takes at most 2 arguments (3 given)```
hushed galleon
#

discord.ui.view is a module, the actual class you want to inherit from is discord.ui.View (capital)
also in the latest version of dpy 2.0, the functions should have a signature of (self, interaction, button), not just (button, interaction)

primal token
shrewd apex
#

also try to have a fixed timeout if the view is not persistent pithink

hushed galleon
#

python scripts are modules

primal token
#

yes?

silk fulcrum
shrewd apex
#

noid just loves providing opinions pithink

silk fulcrum
hushed galleon
pulsar solstice
hushed galleon
#

discord would require the format of <:NAME:ID> then, e.g. python becomes !python

#

you can type your emoji with a prefixed backslash to see that custom emoji format

pulsar solstice
#

it actually works in my server but if u are sayin then I should apply it

#

I was too lazy to do that irl

hushed galleon
#

hmm i havent been able to make it work

#

add_reaction() and Button emoji= with ":xyz:" just gives me error code 400

mild nimbus
#

missing 1 required keyword-only argument: 'intents'
what is this?

hushed galleon
#

dpy 2.0 requires you to specify the intents your Client or Bot will use

mild nimbus
#

Simple Bot creation

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

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

Advanced Bot creation

class MyCoolBot(commands.Bot):
def init(self):
intents = discord.Intents.default()
intents.members = True
intents.message_content = True

    super().__init__(
        command_prefix=["!", "?"],
        description="My Cool Bot!!!",
        intents=intents,
    )
silk fulcrum
mild nimbus
#

oh

silk fulcrum
#

and understand

#

programming is not just copypaste

#

sometimes you have to think ig

rare echo
hushed galleon
#

hey your example actually enables message_content this time
(i mean in comparison to !intents which uses commands.Bot but without message content)

silk fulcrum
pulsar solstice
#
  File "C:\Users\8ster\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ui\view.py", line 423, in _scheduled_task
    await item.callback(interaction)
  File "c:\Users\8ster\OneDrive\Desktop\projects\Discord Bots\Mighty Raju Bot\main.py", line 74, in rock
    embedr=discord.Embed(f"**My move:** {randomrps}\n**Your move:** :dsrock:")
TypeError: Embed.__init__() takes 1 positional argument but 2 were given```
#

what does it mean?

pulsar solstice
silk fulcrum
#

Embed("...") - wrong
Embed(title="...") - right

#

or i think in your case it's description="..."

silk fulcrum
mild nimbus
#

to fix it

silk fulcrum
mild nimbus
#

im new to coding

silk fulcrum
#

!resources @mild nimbus here you can find resources where to learn python

unkempt canyonBOT
#
Resources

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

mild nimbus
#

ty

pulsar solstice
#
  File "C:\Users\8ster\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ui\view.py", line 423, in _scheduled_task
    await item.callback(interaction)
  File "c:\Users\8ster\OneDrive\Desktop\projects\Discord Bots\Mighty Raju Bot\main.py", line 83, in sissors
    await interaction.response.send_message(embed=embeds)
AttributeError: 'Button' object has no attribute 'response'```
#

CODE:

#
class rpsmenu(discord.ui.View):
    def __init__(self) -> None:
        super().__init__()
    embed=discord.Embed(title="RPS" ,description="Choose Your Move", colour=0x552E12)
    @discord.ui.button(label="Rock", style=discord.ButtonStyle.grey, emoji=":dsrock:")
    async def rock(self, button: discord.ui.Button, interaction:discord.Interaction):
        embedr=discord.Embed(description= f"**My move:** {randomrps}\n**Your move:** :dsrock:")
        await interaction.response.send_message(embed=embedr)
    @discord.ui.button(label="Paper", style=discord.ButtonStyle.grey, emoji=":paper:")
    async def paper(self, button: discord.ui.Button, interaction:discord.Interaction):
        embedp=discord.Embed(description=f"**My move:** {randomrps}\n**Your move:** :paper:")
        await interaction.response.send_message(embed=embedp)
    @discord.ui.button(label="Sissors", style=discord.ButtonStyle.grey, emoji=":sissors:")
    async def sissors(self, button: discord.ui.Button, interaction:discord.Interaction):
        embeds=discord.Embed(description=f"**My move:** {randomrps}\n**Your move:** :sissors:")
        await interaction.response.send_message(embed=embeds)

@bot.command()
async def rps(ctx):
    view = rpsmenu()
    embed=discord.Embed(title="RPS" ,description="Choose Your Move", colour=0x552E12)
    await ctx.reply(embed=embed, view=view)
silk fulcrum
#

in your function you do self, button: ..., interaction: ...

#

and it is self, interaction: ..., button: ...

#

or wait i guess nothing changed

#

bruh i have no idea 🗿

silk fulcrum
pulsar solstice
#

I think not?

silk fulcrum
#

i think yes?

pulsar solstice
#

showing this

#

My move: My move: RockMy move: PaperMy move: Sissors
Your move: :dsrock:

pulsar solstice
#

and it is choosing so many outputs

silk fulcrum
#

well actually I do know, you did something wrong in code

pulsar solstice
silk fulcrum
unkempt canyonBOT
#

Hey @pulsar solstice!

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

shrewd apex
#

!e

import random
d = {0: "🪨", 1: "🧻", 2: "✂️"}
def foo(x: int, y:int) -> None:
    z = (x + 1) % 3
    print(f"player move {d[x]}")
    print(f"opponent move {d[y]}")
    if z == y:
        print("p2 won")
    elif x == y:
        print("draw")
    else:
        print("p1 won")
mine = random.randint(1,3)
opp = random.randint(1,3)
foo(mine, opp)
unkempt canyonBOT
#

@shrewd apex :white_check_mark: Your 3.11 eval job has completed with return code 0.

001 | player move 🧻
002 | opponent move ✂️
003 | p2 won
shrewd apex
#

yaytada

primal token
primal token
shrewd apex
primal token
shrewd apex
#

match case works with == in their cases?

primal token
paper sluice
#

enable message_content intent, if you are on dpy 2.0

shrewd apex
#

i think for using == i would have to do something like True if x == y iirc

shrewd apex
#

oh ok i see

paper sluice
#

what did you change?

#

I mean in your code

lone hazel
#

nothing

paper sluice
#

intent.message_content = True

#

add that

lone hazel
#

now work ty

pulsar solstice
#

I want my bot to send a message in a class()

vocal snow
#

!d discord.abc.Messageable

unkempt canyonBOT
#

class discord.abc.Messageable```
An ABC that details the common operations on a model that can send messages.

The following classes implement this ABC...
vocal snow
#

You can send with objects of any classes that implement this

pulsar solstice
#

like this?

vocal snow
#

No what

silk fulcrum
#

lol

pulsar solstice
#

yo pls don't make fun of me now

#

T-T

vocal snow
#

It's kinda funny tho lol

paper sluice
vocal snow
#

!d discord.InteractionResponse

unkempt canyonBOT
#

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

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

New in version 2.0.
paper sluice
#

in the callback, the decorator passes in a discord.Interaction object, you can use that to send messages ^

vocal snow
radiant parrot
#

Some reason this is not muting the user? ```py
async def send_mute(user, reason: str):
channel = client.get_channel(925912014398844998) # channel mute case put in
em = discord.Embed(title="MUTED",
color=discord.Color.red())
em.add_field(name='Member:', value=f'{user}')
em.add_field(name='Duration:', value='1 day')
em.add_field(name='Reason:', value=f'{reason}')
em.set_footer(text=f'Provided by Donks#1048 • {current_time}')
em2 = discord.Embed(title="MUTED", description=f"You have been muted because: {reason}",
color=discord.Color.red())
await channel.send(embed=em)
await user.send(embed=em2)

@client.command()
@has_permissions(manage_channels=True)
async def mute(user: discord.Member):
date = datetime.utcnow() + timedelta(minutes=1440)
await user.timeout(date)```

#
        await interaction.response.send_message(f'Disapproved and muted user!')
        await send_mute(message.author, f'Suggesting non-needed post for #{channel_sent_in}')```
vocal snow
#

!d discord.Member.timeout

unkempt canyonBOT
#

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

Applies a time out to a member until the specified date time or for the given [`datetime.timedelta`](https://docs.python.org/3/library/datetime.html#datetime.timedelta "(in Python v3.10)").

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

This raises the same exceptions as [`edit()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member.edit "discord.Member.edit").
vocal snow
#

Is it timezone aware dt

silk fulcrum
#

dont u need a ctx arg pithink

slate swan
#

anyway i can get ctx from interaction

vocal snow
radiant parrot
slate swan
# vocal snow What are you going to do with the ctx

tryna make a an interaction check but im using slash commands so like idk what to do:

class Butto(nextcord.ui.View):
    def __init__(self, ctx):
        super().__init__()

        self.ctx = ctx

    async def interaction_check(self, interaction):  
        return self.ctx.author == interaction.user

    @nextcord.ui.button(
            label = "Send",
            custom_id="send",
            style=nextcord.ButtonStyle.green,
            row=1
        )

    async def send(self, button: nextcord.ui.Button, interaction: nextcord.Interaction):
        embed = nextcord.Embed(
            description="eeeee"
        )
        await interaction.response.send_message(embed=embed)

class Tester(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
 
    @nextcord.slash_command(description="📜 test shit")
    async def create(self, interaction: nextcord.Interaction):
        view = Butto(ctx = interaction.)
        embed = nextcord.Embed(
            description="jhdhjehked"
        )
        await interaction.response.send_message(embed=embed, view=view)
vocal snow
#

And add ctx param like master said

vocal snow
#

Just pass the original interaction to the view and check if the users are the same

slate swan
#

huh

silk fulcrum
#

ctx=interaction. pithink

#

what is . here

#

and why ctx= if its not a kwarg

radiant parrot
feral frost
#

guys how do i use ephemeral messages ?

radiant parrot
slate swan
#

i was looking at how other ppl had "got ctx from interaction" and they did some other thing

silk fulcrum
feral frost
#

the messages only a person can see when clicking a button for example .

vocal snow
silk fulcrum
unkempt canyonBOT
#
await send(content=None, *, tts=False, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, ...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Sends a message to the destination with the content given.

The content must be a type that can convert to a string through `str(content)`. If the content is set to `None` (the default), then the `embed` parameter must be provided.

To upload a single file, the `file` parameter should be used with a single [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File "discord.File") object. To upload multiple files, the `files` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.10)") of [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File "discord.File") objects. **Specifying both parameters will lead to an exception**.

To upload a single embed, the `embed` parameter should be used with a single [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed "discord.Embed") object. To upload multiple embeds, the `embeds` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.10)") of [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed "discord.Embed") objects. **Specifying both parameters will lead to an exception**.
silk fulcrum
#

ephemeral kwarg

#

that's for dpy

vocal snow
#

Wrong doc

feral frost
silk fulcrum
#

gash

#

i always forget

radiant parrot
silk fulcrum
#

!d discord.InteractionResponse.send_message

unkempt canyonBOT
#

await send_message(content=None, *, embed=..., embeds=..., file=..., files=..., view=..., tts=False, ephemeral=False, allowed_mentions=..., suppress_embeds=False)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Responds to this interaction by sending a message.
vocal snow
feral frost
vocal snow
#

And add ctx param

silk fulcrum
#

here ephemeral arg

radiant parrot
# vocal snow Yes pass that directly
@client.command()
@has_permissions(manage_channels=True)
async def mute(user: discord.Member):
    date = timedelta(minutes=1440)
    await user.timeout(date)``` better?
slate swan
#

hi does anyone know how i can remove all those its not error its just if user don t have role member it do that

#

all red

vocal snow
radiant parrot
#
@client.command()
@has_permissions(manage_channels=True)
async def mute(user: discord.Member, ctx):
    date = timedelta(minutes=1440)
    await user.timeout(date)```?
radiant parrot
#

am i forgetting something

silk fulcrum
#

yes you are

feral frost
#

discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: 'Context' object is not callable

radiant parrot
#

ah

feral frost
#

my code

@bot.command() async def test(ctx): await ctx(content="hi", ephemeral=False)

radiant parrot
silk fulcrum
feral frost
#

send smth

#

ah do i have to do it with interactions

silk fulcrum
silk fulcrum
feral frost
#

ah ok thanks

#

ill tell you when it doesnt work

slate swan
feral frost
vocal snow
silk fulcrum
vocal snow
#

And actual error

silk fulcrum
#

i cant say what is wrong with just "interaction failed"

unkempt canyonBOT
#

Hey @feral frost!

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

feral frost
#

silk fulcrum
#

at least that is how it was for me

feral frost
#

discord.errors.NotFound: 404 Not Found (error code: 10062): Unknown interaction

radiant parrot
feral frost
#

`await interaction.response.send_message(content="test", ephemeral=True)

ticket.callback = button_callback

view = View()
view.add_item(ticket)

await ctx.send(view=view)`
lethal patio
#

how to check whether the person who sent the command and the person who interacted with a button in that message the same person or not?

vocal snow
feral frost
#

its for a ticket system @silk fulcrum

radiant parrot
feral frost
radiant parrot
feral frost
#

my whole code

radiant parrot
#
@client.command()
@has_permissions(manage_channels=True)
async def mute(user: discord.Member, ctx):
    date = timedelta(minutes=1440)
    await user.timeout(date)```
silk fulcrum
#

I think that is because it takes longer than 3 seconds to respond to the interaction when the user clicks the button, await interaction.response.defer() to avoid that

vocal snow
feral frost
#

just put it under there ?

#

or edit it ?

silk fulcrum
#

of callback

feral frost
#

k

#

lets see

radiant parrot
vocal snow
#

Yes

feral frost
#

discord.errors.InteractionResponded: This interaction has already been responded to before

#

i get this error now

radiant parrot
vocal snow
feral frost
silk fulcrum
#

i've not idea actually

silk fulcrum
#

try sending the message at the start of the callback

#

you can remove a defer then

feral frost
#

k lets see

#

and

feral frost
#

IT WORKS

#

THANKU

feral frost
#

you need intents

#

nah no one is dum here

silk fulcrum
#

yeah only me

feral frost
#

i can explain how to set the intents

feral frost
silk fulcrum
#

🗿

#

reset the token pithink

sick birch
#

Might want to reset your token

shrewd apex
#

he didn't reveal the whole thing tho pithink

silk fulcrum
#

that is a token anyways tho pithink

shrewd apex
#

eh fair enough

#

uninstall and install again

sick birch
#

Yeah that’s like telling everyone 9 out of 10 characters in your password

silk fulcrum
#

lmao

shrewd apex
#

who so jobless to brute force the rest

sick birch
#

Great that leaves us about 35 possibilities, should be able to brute force you in.. let’s see.. 20 milliseconds

feral frost
#

less

shrewd apex
#

💀

feral frost
shrewd apex
feral frost
#

🙂

shrewd apex
#

it looks like one of those medical dummies in hospital

silk fulcrum
#

lol

feral frost
#

lmao

sick birch
#

Very awkward

slate swan
#
2022-09-09 19:10:20 INFO     discord.client logging in using static token
2022-09-09 19:10:21 INFO     discord.gateway Shard ID None has connected to Gateway (Session ID: 6122749679dfcb88596b412fdb8b5d9b).
Bot is connected to all of the available servers in the bots mainframe.
2022-09-09 19:10:44 ERROR    discord.ext.commands.bot Ignoring exception in command None
discord.ext.commands.errors.CommandNotFound: Command "unban" is not found

i run my main.py and it works fine as you can see before "Bot is connected" but then when i try to do the command which is ",unban" following with the member's discord id, then it brings an error (the command is in my cogs file)

#

heres the start and end of cogs

primal token
slate swan
#

Traceback (most recent call last):
File "", line 13, in <module>
client = commands.Bot(command_prefix="!")
TypeError: init() missing 1 required keyword-only argument: 'intents'

primal token
#

!d discord.ext.commands.Bot.load_extension

unkempt canyonBOT
#

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

Loads an extension.

An extension is a python module that contains commands, cogs, or listeners.

An extension must have a global function, `setup` defined as the entry point on what to do when the extension is loaded. This entry point must have a single argument, the `bot`.

Changed in version 2.0: This method is now a [coroutine](https://docs.python.org/3/glossary.html#term-coroutine "(in Python v3.10)").
primal token
#

You shouldnt load cogs inside of on_ready either as its prone to errors

shrewd apex
#

it's ppl who ran pip install -U discord.py

slate swan
slate swan
slate swan
slate swan
primal token
slate swan
slate swan
#

huh

#

hi does anyone know how i can remove all those its not error its just if user don t have role member it do that

slate swan
primal token
unkempt canyonBOT
#

discord.ext.commands.on_command_error(ctx, error)```
An error handler that is called when an error is raised inside a command either through user input error, check failure, or an error in your own code.

A default one is provided ([`Bot.on_command_error()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.on_command_error "discord.ext.commands.Bot.on_command_error")).
sick birch
#

You need to take a more hands on approach with classes

#

Conceptually they can be difficult to learn so watching someone else talk about it in a video won’t help much

primal token
slate swan
slate swan
sick birch
#

You need to actively try to implement it wherever you can

primal token
slate swan
primal token
slate swan
# primal token Well maybe read up on it again, can you provide which tutorial you followed?

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

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

▶ Play video
#

it has 6 parts

primal token
slate swan
#

ERROR: Could not find a version that satisfies the requirement bot (from versions: none)
ERROR: No matching distribution found for bot
WARNING: You are using pip version 21.2.4; however, version 22.2.2 is available.
You should consider upgrading via the 'C:\AppData\Local\Programs\Python\Python39\python.exe -m pip install --upgrade pip' command.

slate swan
slate swan
vestal dagger
primal token
slate swan