#discord-bots

1 messages · Page 272 of 1

potent spear
#

and it looks like it's blocking too

void mauve
#

concerned
discord.app_commands.errors.CommandInvokeError: Command 'rec' raised an exception: AttributeError: 'Interaction' object has no attribute 'defer'

potent spear
void mauve
#

well i got the output but bot still thinkin

potent spear
#

releasing & destroying might take a while?

void mauve
#

it waits only 5 seconds after releasing, but hes still in a deep thoughts

potent spear
#

no idea what you mean by that

void mauve
#

he still sent no embed

#

thats the point

potent spear
#

small rewrite note

await find_channel("💻-screen").send(file=discord.File(output_file))

    embed = discord.Embed(title="Recording has been made!",
                          description=f"Check it out at <#{find_channel_id('💻-screen')}>",```
---
```py
channel = await find_channel("💻-screen")

await channel.send(file=discord.File(output_file))

    embed = discord.Embed(title="Recording has been made!",
                          description=f"Check it out at {channel.mention}",```
void mauve
#

oh thanks

potent spear
void mauve
potent spear
#

    # no sending of file in a separate message anymore 
    # ... send(file=...)

    embed = discord.Embed(title="Recording has been made!",
                          description=f"Check it out at {channel.mention}",
                          colour=embed_color,
                          timestamp=datetime.now())

    embed.set_footer(text="SnoopRat",
                     icon_url=SnoopRat_icon)

  # file gets sent together with embed
    await interaction.followup.send_message(file=discord.File(output_file), embed=embed)
#

you do realize that probably while your screen is recording, that you're blocking your bot from doing other things because the video writer writes sync instead of async?

potent spear
#

try any other command WHILE your bot is recording, you'll see

void mauve
#

yeah ik, so how do i fix it then Concern btw heres the console output now RuntimeWarning: Enable tracemalloc to get the object allocation traceback

potent spear
#

you're not awaiting a certain line

potent spear
potent spear
#

gl hf

red bough
#

can someone help me with discord bot im almost done just have 1 problem dm me,

lofty lance
#

hey sir u free?
need some help

red bough
#

no i fixed thanks doe

slate swan
#

can anyone help me with that error on replit please :

slate swan
#

There is no package libs.solver

slate swan
#

Is anyone experienced with hypixel api im trying to make a bot that needs to get allthe stats and stuff for an account

#

When i try to use it it does this

#

Gets none of the account stats/info

slate swan
#

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

Liek what it says in terminal on VSC?

#
def get_player_data(username):
    url = f"https://api.hypixel.net/player?key={api_key}&name={username}"
    response = requests.get(url)

    if response.status_code == 200:
        data = response.json()
        print(data)
        if data.get('success'):
            return data['player']
    return None
naive briar
#

(also, requests is blocking, use an asynchronous library instead)

harsh orbit
#
import discord
from discord.ext import commands
import os

intents= discord.Intents.all()

bot = discord.ext.commands.Bot("!", intents=intents)
Token = os.environ['token']

@bot.event
async def on_ready():
  print("Bot Online")

@bot.event
async def on_member_join(member):
  join_channel_id = 1028256485383344170
  join_channel = bot.get_channel(join_channel_id)
  member = str(member.mention)
  await join_channel.send(member + " is here")

@bot.event
async def on_member_remove(member):
  leave_channel_id = 1028256485383344170
  leave_channel = bot.get_channel(leave_channel_id)
  member = str(member.mention)
  await leave_channel.send('GoodBuy ' + member)


@bot.command(pass_contaxt = True)
async def joinme(ctx):
 if (ctx.author.voice):
   voice_channel = ctx.message.author.voice.channel
   await voice_channel.connect()

bot.run(Token)
#

this shows when I type
!joineme

#

Hello?

#

@slate swan

#

....

#

Please anyone help me

vale wing
harsh orbit
#

import?

vale wing
#

Run in shell

harsh orbit
#

It's repl it

vale wing
#

Yes

#

Replit has shell

harsh orbit
#

Ok I will try

vale wing
#

And yeah if possible switch to desktop, it's heaven compared to mobile coding

harsh orbit
#

I don't have pc

harsh orbit
vale wing
#

That is exactly how you type it

harsh orbit
vale wing
#

Ight try pip install discord.py[voice]

#

Replit is screwed, on mobile it's screwed even more

harsh orbit
#

Still the same error @vale wing

vale wing
#

pip install pynacl

harsh orbit
#

Finally it worked

#

Thx a lot

harsh orbit
#
import discord
from discord.ext import commands
import os

intents= discord.Intents.all()

bot = discord.ext.commands.Bot("!", intents=intents)
Token = os.environ['token']

@bot.event
async def on_ready():
  print("Bot Online")

@bot.event
async def on_member_join(member):
  join_channel_id = 1028256485383344170
  join_channel = bot.get_channel(join_channel_id)
  member = str(member.mention)
  await join_channel.send(member + " is here")

@bot.event
async def on_member_remove(member):
  leave_channel_id = 1028256485383344170
  leave_channel = bot.get_channel(leave_channel_id)
  member = str(member.mention)
  await leave_channel.send('GoodBuy ' + member)


@bot.command(pass_contaxt = True)
async def joinme(ctx):
 if (ctx.author.voice):
   voice_channel = ctx.message.author.voice.channel
   await voice_channel.connect()
   await ctx.send("Ok")

 else:
   ctx.send("You aren't in voice channel")

@bot.command(pass_contaxt = True)
async def leave(ctx):
  if (ctx.voice_client):
    await ctx.guild.voice_client.disconnect
    await ctx.send("I left the voice channel")

  else:
      await ctx.send("I'm not in voice channel")

bot.run(Token)
#

When
!leave

#

I tried to remove await

#

But it didn't work

#

No errors but the command not joining the channel

naive briar
harsh orbit
naive briar
#

Yes?

slate swan
harsh orbit
#
from discord.ext import has_premissions, MissingPermissons

What did it mean wrong location?

buoyant quail
harsh orbit
#

What??

#

I used them before

buoyant quail
#

They are inside commands/app_commands

harsh orbit
buoyant quail
#

No, i can't logo_ironpython

vocal laurel
#

mayi?

buoyant quail
#

he should get it by himself :p

vocal laurel
#

ok.

#

btw when u do from ... import .. do u understnad what it means?

harsh orbit
#

._.

#

Ok ok thx

buoyant quail
#

Also you have a typo MissingPermissons -> MissingPermissions

slate swan
#

?

#

import requests
import discord
import datetime
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.options import Options
import time
from PIL import Image
from discord import app_commands

MY_GUILD = discord.Object(id=1121927606154043498)
class MyClient(discord.Client):
def init(self, *, intents: discord.Intents):
super().init(intents=intents)
self.tree = app_commands.CommandTree(self)

async def setup_hook(self):
    self.tree.copy_global_to(guild=MY_GUILD)
    await self.tree.sync(guild=MY_GUILD)

intents = discord.Intents.default()
client = MyClient(intents=intents)

@app_commands.describe(
ip='The IP you wish to locate',
)

async def locates(interaction: discord.Interaction, ip: str):
await interaction.response.defer(ephemeral=True, thinking=True)
try:
if interaction and interaction.message and interaction.message.channel:
if interaction.message.channel.type == discord.ChannelType.private:
await interaction.send('My apologies, but you cannot use this command in private messages.')
else:
ip_url = f"https://tools.keycdn.com/geo.json?host={IP}"
headers = {
"User-Agent": "keycdn-tools:https://beta.octosniff.net/"
}
ip_response = requests.get(ip_url, headers=headers)
data = ip_response.json()
# Extract the required information
city = data['data']['geo']['city']
state = data['data']['geo']['region_name']
country = data['data']['geo']['country_name']

        # Print the city, state, and country
        await interaction.user.send(f"{IP} is located in {city}, {state}, {country}")

except:
    print("Fucked")

The slash commands are not showing up in my discord

thin raft
#

did you sync?

#

ok yeah

#

!paste

unkempt canyonBOT
#
Pasting large amounts of code

If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/

After pasting your code, save it by clicking the Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.

naive briar
slate swan
naive briar
#

What modules

slate swan
slate swan
#

@thin raft

vocal laurel
#

Remove ur token

#

@slate swan

whole fable
#

hello

vocal laurel
#

Hi

whole fable
#

dev means developer

vocal laurel
#

Yes

whole fable
#

lanqu nice name

vocal laurel
#

Oh thanks

whole fable
#

python turtle

slate swan
vocal laurel
#

U also got a nice name PranavDEV

whole fable
#

tnks

vocal laurel
#

Do u need help with anything?

whole fable
#

yes

#

what do you know

vocal laurel
whole fable
#

plz tell me

#

ok

vocal laurel
#

Cuz Yk this is for discord bots

whole fable
#

are you ai

vocal laurel
#

What no

whole fable
#

kidding

vocal laurel
#

Why did u ask that..

whole fable
#

joke

vocal laurel
#

Yes Ik

whole fable
#

pk do you know chatGPT

vocal laurel
#

Yes

whole fable
#

so you are developing discord bots with python

vocal laurel
#

Yes

slate swan
whole fable
#

where are you from

vocal laurel
#

There is a whole discord server for that

vocal laurel
whole fable
#

itz okkkkie

slate swan
vocal laurel
#

Ye sorry

slate swan
#

👍

whole fable
#

i want some frnds to lrn py

slate swan
whole fable
#

so tring to mke frnds

vocal laurel
whole fable
#

ok

slate swan
whole fable
#

i am a big developer in python i know print(''lanqu') only🙃

slate swan
slate swan
slate swan
#

and someone nuked my discord

vocal laurel
slate swan
#

great

vocal laurel
#

Bru

#

As soon as i told u

slate swan
#

i changed it

vocal laurel
slate swan
#

right when u said it

slate swan
vocal laurel
#

So u gave ppl access to ur bot for 1 hr

slate swan
vocal laurel
slate swan
vocal laurel
slate swan
vocal laurel
slate swan
#

"Nuked"

vocal laurel
#

Oof

#

How many members?

slate swan
#

only 60

#

fatherless

vocal laurel
slate swan
#

the person that nuked

vocal laurel
vocal laurel
slate swan
#

i just sell a bunch of bots that help ppl pull fn accounts

#

lol

vocal laurel
#

Lol

#

Btw what’s fn?

slate swan
#

fortnite

vocal laurel
#

Oh nvm lol

unkempt canyonBOT
#

5. Do not provide or request help on projects that may violate terms of service, or that may be deemed inappropriate, malicious, or illegal.

slate swan
vocal laurel
slate swan
#

depends what you mean by pull fortnite accounts

slate swan
slate swan
vocal laurel
#
  • he wasn’t asking for help
slate swan
slate swan
#

he was before

slate swan
slate swan
vocal laurel
vocal laurel
slate swan
#

that was a bad gif

vocal laurel
#

But he never asked for help

#

Ok anyways down can u help him?

vocal laurel
slate swan
#

ty @vocal laurel

vocal laurel
#

Np

slate swan
#

whats wrong with it?

slate swan
#

full traceback

#

lost it

#

running 1 sec

#

Traceback (most recent call last):
File "C:\Users\Josh\Desktop\Ultimate\ULTIMATE.py", line 32, in <module>
async def locateip(interaction: discord.Interaction, ip: str):
File "C:\Users\Josh\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\app_commands\tree.py", line 887, in decorator
command = Command(
File "C:\Users\Josh\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\app_commands\commands.py", line 666, in init
self._params: Dict[str, CommandParameter] = _extract_parameters_from_callback(callback, callback.globals)
File "C:\Users\Josh\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\app_commands\commands.py", line 389, in _extract_parameters_from_callback
_populate_descriptions(result, descriptions)
File "C:\Users\Josh\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\app_commands\commands.py", line 277, in _populate_descriptions
raise TypeError(f'unknown parameter given: {first}')
TypeError: unknown parameter given: item

buoyant quail
#

Your command has only ip parameter

slate swan
#

a command to track down ip?

buoyant quail
#

And you are describing some others

slate swan
slate swan
slate swan
#

one is mentioned later

#

so describe the other one

#

it is

#

no the second one is not even a command

#

you are missing decorators here

#

wdym

#

if you want to define a command you decorate a function with @client.tree.command() in this case

#

you only do it for one function

#

hence you have one command

#

so how do I add a second command?

slate swan
#

im new idk what that means

#

can u show me an example?

#

but you already did this?

#

gpt

#

lol

#

..

#

you need at least python basics to create a discord bot gpt is not enough

#

ik basics

#

by basics i mean decorators

unkempt canyonBOT
#
Decorators

A decorator is a function that modifies another function.

Consider the following example of a timer decorator:

>>> import time
>>> def timer(f):
...     def inner(*args, **kwargs):
...         start = time.time()
...         result = f(*args, **kwargs)
...         print('Time elapsed:', time.time() - start)
...         return result
...     return inner
...
>>> @timer
... def slow(delay=1):
...     time.sleep(delay)
...     return 'Finished!'
...
>>> print(slow())
Time elapsed: 1.0011568069458008
Finished!
>>> print(slow(3))
Time elapsed: 3.000307321548462
Finished!

More information:
Corey Schafer's video on decorators
Real python article

slate swan
#

can u give me an example of what it would look like to add a second command?

#
@client.tree.command()
@app_commands.describe(...)
async def first_command(interaction, ...):
    ...
#

you do this for each command

slate swan
#

line 1 especially

#

line 2 is just to give description its not needed

#

it wont fuck up my first cmd?

#

why would it?

#

idk im a paranoid person

#

try and see

#

alright

#

will update!

#

worked, just 1 more issue arising dk what its about

slate swan
# slate swan worked, just 1 more issue arising dk what its about

File "C:\Users\Josh\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\app_commands\commands.py", line 828, in _do_call
return await self._callback(interaction, **params) # type: ignore
File "C:\Users\Josh\Desktop\Ultimate\ULTIMATE.py", line 69, in receipt
datetime_object = datetime.strptime(date, '%m/%d/%Y')
AttributeError: module 'datetime' has no attribute 'strptime'

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
File "C:\Users\Josh\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\app_commands\tree.py", line 1248, in _call
await command._invoke_with_namespace(interaction, namespace)
File "C:\Users\Josh\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\app_commands\commands.py", line 853, in _invoke_with_namespace
return await self._do_call(interaction, transformed_values)
File "C:\Users\Josh\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\app_commands\commands.py", line 846, in _do_call
raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'receipt' raised an exception: AttributeError: module 'datetime' has no attribute 'strptime'

#

!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*.

If *format* does not contain microseconds or timezone information, 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. See also [strftime() and strptime() Behavior](https://docs.python.org/3/library/datetime.html#strftime-strptime-behavior) and [`datetime.fromisoformat()`](https://docs.python.org/3/library/datetime.html#datetime.datetime.fromisoformat "datetime.datetime.fromisoformat").
slate swan
#

its datetime.datetime

#

its just that it worked when ti was not a discord bot

#

maybe you imported from datetime import datetime

#

and now you did import datetime

#

yep

#

why tf are u so smart wth

#

glad to hear that

livid hedge
#

hello guys, I am trying to add a cog to my python discord bot.
This is my bot's class

class Bot(commands.Bot):
        def __init__(self, command_prefix, intents, self_bot=False):
            commands.Bot.__init__(self, command_prefix=command_prefix, intents=intents, self_bot=self_bot)
            self.add_cog(General_commands(self))

This is my cog class

class General_commands(commands.Cog): # addded commands.Cog after "Down" suggestion
    def __init__(self, bot):
        self.bot = bot

    @commands.command
    async def status(self, ctx):
        await ctx.send('Bot is online!')

This line -> self.add_cog(General_commands(self)) in Bot's class throw this warning "RuntimeWarning: coroutine 'BotBase.add_cog' was never awaited" that basically says that I have to await that function call ( which I read too on stackoverflow ). If I add the "await" statement ( so it becomes await self.add_cog(General_commands(self)) ) I get the error "SyntaxError: 'await' outside async function".

It doesn't work in any way. I mind if I placed the add_cog to the wrong place. I tried to place it even outside the __init__ method, so in the main, but I still get the warning "cog was never awaited".

Does anyone suggest any solution? I would appreciate it a lot

slate swan
#

First of all the class must be a subclass of commands.Cog

livid hedge
#

right!

slate swan
#

second thing

#

you need to call @commands.command

#

third thing

#

the .add_cog is awaiable

#

meaning you need to await it

livid hedge
slate swan
#

you just need to add ()

livid hedge
slate swan
#

so load it in setup_hook or else

livid hedge
#

I have to async the init

slate swan
#

init cant be async

livid hedge
#

okay

slate swan
#

override the setup_hook method

#

and load it here

#

!d discord.ext.commands.Bot.setup_hook

unkempt canyonBOT
#

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

A coroutine to be called to setup the bot, by default this is blank.

To perform asynchronous setup after the bot is logged in but before it has connected to the Websocket, overwrite this coroutine.

This is only called once, in [`login()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.login "discord.ext.commands.Bot.login"), and will be called before any events are dispatched, making it a better solution than doing such setup in the [`on_ready()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_ready "discord.on_ready") event.

Warning

Since this is called *before* the websocket connection is made therefore anything that waits for the websocket will deadlock, this includes things like [`wait_for()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.wait_for "discord.ext.commands.Bot.wait_for") and [`wait_until_ready()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.wait_until_ready "discord.ext.commands.Bot.wait_until_ready")...
livid hedge
#

now it works without errors, I just get Command "status" is not found

slate swan
#

how do you load the cog?

livid hedge
#
# inside bot's class
        async def setup_hook(self) -> None:
            await self.add_cog(General_commands(self))
slate swan
#

okay and did you change the thing with @commands.command i told you to

livid hedge
#

Yes, now it works

#

Thank you very much Down!

slate swan
#

👍

thorn grove
#

uhmm when i add a on_message(), my @client.command() doesnt work anymore

#

why?

#

when i remove on_message() the command works fine tho

dry sedge
thorn grove
slate swan
#

Btw im using replit

turbid condor
#

What is even module1 and module2?

buoyant quail
#

Because such module doesn't exist

slate swan
#

because there is the modules is writed on the script and i have to install it to launch the script

buoyant quail
#

What

#

Which modules you want to install

slate swan
buoyant quail
slate swan
slate swan
buoyant quail
slate swan
slate swan
#

and looks like this modules are those

slate swan
#

but it's a friend's script @buoyant quail

buoyant quail
#

then ask friend :/

slate swan
buoyant quail
#

xd

golden portal
#

its from a github repo called Discord-Token-Generator, its indeed from a folder called libs

livid hedge
#

It's always me. How can I add slash commands using discordpy?

buoyant quail
#

unpack libs.zip

#

and rule 5

slate swan
#

can we even help with it

buoyant quail
#

!rule 5

unkempt canyonBOT
#

5. Do not provide or request help on projects that may violate terms of service, or that may be deemed inappropriate, malicious, or illegal.

slate swan
buoyant quail
livid hedge
slate swan
# unkempt canyon

@buoyant quail creating discord tokens do not respect discord TOS ?

slate swan
golden portal
slate swan
slate swan
golden portal
slate swan
#

ah shit ook thanks anyway @slate swan @buoyant quail sugar daddys Hearts

buoyant quail
#

sugar daddys 💀

cunning iris
#

how can I remove the "this interaction failed" from dropdowns (considering everything works fine apart from this weird message) ?

#

without using interactions

buoyant quail
unkempt canyonBOT
#

:incoming_envelope: :ok_hand: applied timeout to @whole fable until <t:1689778565:f> (10 minutes) (reason: attachments spam - sent 10 attachments).

The <@&831776746206265384> have been alerted for review.

buoyant quail
#

ten attachments brainmon

cunning iris
# buoyant quail Respond something to interaction or defer it.

just told I didn't use interactions. This is my code

class biome_selection(discord.ui.Select):
    def __init__(self, userid):
        options = [discord.SelectOption(label="Swamp"),
                   discord.SelectOption(label="Desert"),
                   discord.SelectOption(label="Woods")]
        super().__init__(placeholder="What biome do you chose ?", options=options)
        self.userid = userid

    async def callback(self, ctx):
        if ctx.user.id == self.userid:
            await ctx.message.channel.send(content=f"{ctx.user.mention} successfully chose {self.values[0]}")


class Drop(discord.ui.View):
    def __init__(self, userid, name: str):
        super().__init__()
        if name == request.classSelection():
            self.add_item(class_selection(userid))
        elif name == request.biomeSelection():
            self.add_item(biome_selection(userid))
        # TODO : add the remaining selections

request is just a class containing a few strings to handle the (many) dropdown menus. The call in my main file looks like this, right now it's just testing :

@bot.command(name = "biome")
async def test(ctx):
    view = Drop(ctx.message.author.id, request.biomeSelection())
    await ctx.message.channel.send(ctx.message.author.mention + "choose a biome", view=view)```
buoyant quail
cunning iris
#

you mean I can just do ctx: discord.Interaction and it'll work ? or ctx is instantely recognized as an interaction

buoyant quail
#

Typehints doesn't matter

#

use ctx.response.send_message instead of your send

cunning iris
#

oh alright thanks

slate swan
#

how can i make bot using python

buoyant quail
fringe sluice
#

Hi

#

what

#

censored?>

#

So i'm making a discord bot that is powered by chatgpt and i can't seem to get the bot to send a message

#

What

#

can't send py? wt

#

Sorry but best format i can send...

print("command warn") print(friendly_message) async def get_channel(): channel = bot.get_channel(1077629150262730814) asyncio.run(get_channel()) await channel.send(friendly_message) print("sent message to channel",channel)

#

tried looking on stackoverflow, but thats the best i could find and doesn't work

buoyant quail
#

And where you call get_channel function? Except inside itself

fringe sluice
#

Oh let me pull up the full code

buoyant quail
#

I guess you don't because you'd got an infinite recursion

fringe sluice
#

async def get_channel(): ?

buoyant quail
#

yes

fringe sluice
#

yes?

buoyant quail
#

You defined the function. It won't run until you will call it.

fringe sluice
#

Oh so all i need is to call it?

buoyant quail
#

Yeah

fringe sluice
#

oooh

buoyant quail
#

And remove asyncio.run(get_channel()) from it

#

Because it will call itself infinitely

fringe sluice
#

'ill see if it works 👀

fringe sluice
#

elif command == "warn":
print("command warn")
print(friendly_message)
async def get_channel():
channel = bot.get_channel(1077629150262730814)

                await channel.send(friendly_message)
            get_channel()
            print("sent message to channel")
buoyant quail
#

It's an async function, you need to await it

#

await get_channel()

fringe sluice
#

got it

buoyant quail
#

actually you can just get the code out from function

#

because it's kinda useless here

fringe sluice
#

huh i get invalid syntax

fringe sluice
#

werid, so i went before on discord.py documentation and just copied their send message in channel snippet but it seems to need something to be defined

buoyant quail
#

?

fringe sluice
#

i removed the function as you said

#

i will try again

#

yeah works now

#

😄

cunning iris
#

ok I'm probably blind but I don't seem to find the way to make a dropdown menu clickable a single time by a user in the doc, what's the magic line to do that

buoyant quail
#

Just delete/disable it in the callback

cunning iris
#

that would make it clickable a single time

#

I meant a user could only use the menu once

#

and any other user could use it, but a single time too

buoyant quail
#

Such thing doesn't exist in discord itself, implement it by yourself

#

Remember the users who clicked inside and don't answer them next times

fringe sluice
#

I have one more question... How would i go on banning kicking and muting a member. Would like reason too to msg dm the user

turbid condor
#

!d discord.Member

unkempt canyonBOT
#

class discord.Member```
Represents a Discord member to a [`Guild`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild "discord.Guild").

This implements a lot of the functionality of [`User`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User "discord.User").

x == y Checks if two members are equal. Note that this works with [`User`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User "discord.User") instances too.

x != y Checks if two members are not equal. Note that this works with [`User`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User "discord.User") instances too.

hash(x) Returns the member’s hash.

str(x) Returns the member’s handle (e.g. `name` or `name#discriminator`).
cunning iris
fringe sluice
#

i'm not that familar with guild...

#

can you just do it by user? <@>?

#

whats guild anyways

turbid condor
fringe sluice
#

Yeah is there any documentation i can look at to learn more

turbid condor
fringe sluice
#

Ah i see now

turbid condor
fringe sluice
#

is it bc members can have server names and such

turbid condor
fringe sluice
turbid condor
#

!d discord.Guild.ban

unkempt canyonBOT
#

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

Bans a user from the guild.

The user must meet the [`abc.Snowflake`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Snowflake "discord.abc.Snowflake") abc.

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

!d discord.Guild.kick

unkempt canyonBOT
#

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

Kicks a user from the guild.

The user must meet the [`abc.Snowflake`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Snowflake "discord.abc.Snowflake") abc.

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

Thanks

livid juniper
#

someone giving away a very simple bot with slash commands? Pls, I'm new to python programming and old tutorials don't work

fringe sluice
#

maybe when i'm done i can give it to you

foggy crow
#

Hey guys

fringe sluice
foggy crow
#

Do you think Having a Discord bot as a Command center for some personal and work related stuff would be suitable ?

fringe sluice
#

it moderates

foggy crow
#

I'm not sure what to use for this kind of usecases, what do you use in these scenarios?

slate swan
buoyant quail
fringe sluice
#

because thats not even working

#

thats what i got:

if command == "ban":
# Perform action for ban
print("Performing ban action")

                await ban(user, reason=reason, delete_message_days=1, delete_message_seconds=0)
#

@buoyant quail

buoyant quail
#

What is ban

#

How did you define it

fringe sluice
#

would it need to be member.ban?

buoyant quail
#

ye

fringe sluice
#

ok

#

i'm getting UnboundLocalError: local variable 'member' referenced before assignment
does it have to do with my indentation

buoyant quail
#

Where you defined member

#

Every variable you use can't just appear from air

fringe sluice
#

would this work? member = guild.get_member(user["id"])

#

had this part in my code just wasn't using it to ban

buoyant quail
#

maybe
depends on what user is

fringe sluice
#

user = message.author

naive briar
fringe sluice
#

async def on_message(message):

#

wouldn't that provide the user?

naive briar
#

!e

class User:
    pass

user = User()
user["id"]
unkempt canyonBOT
#

@naive briar :x: Your 3.11 eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "/home/main.py", line 5, in <module>
003 |     user["id"]
004 |     ~~~~^^^^^^
005 | TypeError: 'User' object is not subscriptable
buoyant quail
naive briar
#

I bet you'd get the same kind of error

fringe sluice
#

? ok

#

just use the member = guild yadada?

naive briar
#

What?

fringe sluice
#

would i need to provide user id?

#

member = guild.get_member(user["id"]) <=== id?

#

or is that to GET the id?

#

or to input the id no

naive briar
#

You already got the member object from the message object

fringe sluice
#

you mean the when a message is sent?

naive briar
#

And you can already get the user/member object from the message object

#

!d discord.Message.author

unkempt canyonBOT
fringe sluice
fringe sluice
#

but it's under the message function

naive briar
naive briar
fringe sluice
#

what do i define? thats what i'm not getting

naive briar
#

I didn't tell you to define anything

fringe sluice
#

huh

#

but then how do i use member.ban?

#

if member isn't defined

buoyant quail
#

It can be any variable of Member instance

naive briar
#

Get it from the message

buoyant quail
#

Doesn't matter how you name it
You named it user, then use user

fringe sluice
#

? message.author

#

i've got that already and thats equals to user

buoyant quail
#

user.ban

fringe sluice
#

Ok

#

Ok that seems solved, but why does it say it only takes 1 arg? TypeError: ban() takes 1 positional argument but 2 were given

#

i just put await user.ban(user, reason=reason, delete_message_days=1)
TypeError: ban() takes 1 positional argument but 2 were given

#

the documentation even gives 3

naive briar
#

What documention

#

!d discord.Member.ban

unkempt canyonBOT
#

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

Bans this member. Equivalent to [`Guild.ban()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild.ban "discord.Guild.ban").
naive briar
#

The method takes no positional arguments

fringe sluice
#

Yes that see?

fringe sluice
naive briar
#

If Python doesn't raise the SyntaxError then the syntax is correct

fringe sluice
#

sorry my bad didn't mean 'syntax'

naive briar
#

!e

def a(*, b):
    print(b)

a(0)
unkempt canyonBOT
#

@naive briar :x: Your 3.11 eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "/home/main.py", line 4, in <module>
003 |     a(0)
004 | TypeError: a() takes 0 positional arguments but 1 was given
fringe sluice
#

i mean the correct argument useage

naive briar
#

!keyword

unkempt canyonBOT
#
Positional vs. keyword arguments

Functions can take two different kinds of arguments. A positional argument is just the object itself. A keyword argument is a name assigned to an object.

Example

>>> print('Hello', 'world!', sep=', ')
Hello, world!

The first two strings 'Hello' and 'world!' are positional arguments.
The sep=', ' is a keyword argument.

Note
A keyword argument can be passed positionally in some cases.

def sum(a, b=1):
    return a + b

sum(1, b=5)
sum(1, 5) # same as above

Sometimes this is forced, in the case of the pow() function.

The reverse is also true:

>>> def foo(a, b):
...     print(a, b)
...
>>> foo(a=1, b=2)
1 2
>>> foo(b=1, a=2)
2 1

More info
Keyword only arguments
Positional only arguments
/tag param-arg (Parameters vs. Arguments)

fringe sluice
#

Ok i get it

#

but the documentation doesn't make it clear how to actually use it no examples given?

naive briar
#

It doesn't have to

fringe sluice
#

it gives you all the possibilities for arguments

#

but not specific use cases

naive briar
#

What do you mean not specific use cases

#

They can't just give you all possible examples

fringe sluice
#

like not using seconds, no reason given,etc

naive briar
#

You'd already know that if you know Python enough

buoyant quail
#

It shows the parameters definition and explains which parameter what takes and does.

fringe sluice
#

nothing fancy

slate swan
#

hi

fringe sluice
naive briar
#

What command

slate swan
fringe sluice
#

yeah i'm using user.ban

slate swan
#

and what you have already?

fringe sluice
#

user = message.author

slate swan
fringe sluice
#

yeah

slate swan
#

now you have User or Member object

fringe sluice
#

await user.ban(user, reason=reason, delete_message_days=1)

slate swan
#

lucky for you both of them have .ban method

#

wait no

naive briar
#

User have a ban method?

slate swan
#

i just noticed what im saying

slate swan
unkempt canyonBOT
#

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

Bans this member. Equivalent to [`Guild.ban()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild.ban "discord.Guild.ban").
fringe sluice
slate swan
#

so you are doing the ban method on a Member object already

#

so no need to pass user to the method

#

it already knows who to ban

slate swan
fringe sluice
#

what

#

i'm so confused rn

naive briar
#

They take different arguments

#

!d discord.Guild.ban

unkempt canyonBOT
#

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

Bans a user from the guild.

The user must meet the [`abc.Snowflake`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Snowflake "discord.abc.Snowflake") abc.

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

all it does is it references the guild and passes the arguments you have plus the member itself

fringe sluice
#

whats missing in delete_message_days: int = MISSING, here?

slate swan
naive briar
#

It's just a default argument

slate swan
#

you should use delete_message_seconds instead

fringe sluice
#

what if i want days

slate swan
fringe sluice
#

ok so just put the value in missing

slate swan
unkempt canyonBOT
#

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

How many seconds is that?: 36000
slate swan
#

you just dont pass it then its default to it

fringe sluice
#

huh

naive briar
#

A day has 3600 seconds!? 😨

slate swan
#

you know what default values for arguments are in functions?

slate swan
naive briar
#

!e

def a(b = 101):
    print(b)

a(202)
a()
unkempt canyonBOT
#

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

001 | 202
002 | 101
fringe sluice
#

uhhh i'm not getting it

slate swan
#

look above

fringe sluice
#

whats the supposd to be dice_question

slate swan
naive briar
#

The argument will be supplied by the default argument if you don't pass it

slate swan
#

!e ```py
shopping_list = {}

def add_item(item_name, quantity=1):
if item_name in shopping_list.keys():
shopping_list[item_name] += quantity
else:
shopping_list[item_name] = quantity

add_item("Bread")
add_item("Milk", 2)
print(shopping_list)

unkempt canyonBOT
#

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

{'Bread': 1, 'Milk': 2}
slate swan
#

we add item Bread but we did not give quantity so the default value was used (quantity=1) 1 in this case

#

but when adding Milk we provided the quantity so its used instead

#

does that make it clear?

fringe sluice
#

yeah sorta

#

but i still can't understand how to use the ban command 😬

slate swan
#

what you dont understand

#

you just do await member.ban() and optionally you can provide reason and delete_message_seconds

fringe sluice
#

? thats fine

slate swan
#

what do you mean by that

fringe sluice
#

thats fine i don't mind just giving the reason only, but what if i want to provide delete_message_seconds?

naive briar
#

Then provide it?

slate swan
#

then you just provide it?

fringe sluice
slate swan
#

!e ```py
def ban(*, reason=None, delete_message_seconds=None):
print(reason, delete_message_seconds)

ban(reason="some reason")
ban(delete_message_seconds=100)
ban(delete_message_seconds=200, reason="some cool reason")
ban(reason="some other cool reason", delete_message_seconds=300)

unkempt canyonBOT
#

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

001 | some reason None
002 | None 100
003 | some cool reason 200
004 | some other cool reason 300
slate swan
#

you get an error?

fringe sluice
#

Yeah that makes it clear

#

i was doing it wrong

#

await user.ban(user, reason=reason, delete_message_days=1)
TypeError: ban() takes 1 positional argument but 2 were given

#

so should i just define it as a function

slate swan
#

Member.ban does not accept user argument like i said

fringe sluice
#

yeah i removed it

#

await user.ban(reason=reason)

slate swan
#

cool

fringe sluice
#

would you be able to join my server and test the bot? seems that i can't ban my self

sick birch
#

that's what alts are for

#

pretty much everyone who works with discord bots has an alt

slate swan
#

vibecat Hi

fringe sluice
slate swan
#

Can I add two datetime objects?

slate swan
#

You can also subtract a datetime from another datetime to get a timedelta

#

How do I convert a datetime to timedelta?

#

2023-08-18 11:00:54.854651 I need to add this to the current time

slate swan
#

Think about what you're trying to do, adding two datetimes just wouldn't really make any sense

#

Hmm yeah so what would I have to do?

#

Well I wouldn't know unless you gave some more context, it's your code vibecat

slate swan
lyric echo
#

idk if it fits here but just a question - i am doing a bot with a moderation command to change permissions in roles/users. it separates groups of permissions in sort-of linux way (read - read chat log, see channels; write - write messages, speak in channels; etc...). someone knows how i could make a group of such permissions so i can have only 3 sets of such permission groups and then only combine command parameters? right now it looks like this and i dont like it:

    elif arg1 == "3":
      await member.edit(
            permissions=discord.Permissions(embed_links=True,
                                            attach_files=True,
                                            add_reactions=True,
                                            use_external_emojis=True,
                                            send_tts_messages=True,
                                            use_slash_commands=True,
                                            stream=True,
                                            use_voice_activation=True,
                                            priority_speaker=True,
                                            send_messages=True,
                                            speak=True,
                                            change_nickname=True,
                                            create_instant_invite=True))

i'd rather sort of that but idk if its ever possible:

read = ("read_messages"=True, "see_channels"=True)
write=("send_messages"=True, "join_voice"=True)
...
  elif arg1 == "3":
      await member.edit(
            permissions=discord.Permissions(read,write)
slate swan
lyric echo
#

sort of...

slate swan
#

!e ```py
def f(**kwargs):
print(kwargs)

perms = {"embed_links": True, "attach_files": True, "add_reactions": True, "use_external_emojis": True}
f(**perms)

unkempt canyonBOT
#

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

{'embed_links': True, 'attach_files': True, 'add_reactions': True, 'use_external_emojis': True}
lyric echo
#

ok, very thx

slate swan
#

not sure if you can pass the permissions as string though

buoyant quail
lyric echo
#

i know no but looks now like doable

unkempt canyonBOT
#

@buoyant quail :white_check_mark: Your 3.11 eval job has completed with return code 0.

4046-03-05 05:17:50.849624
upbeat ice
#

what about using enums?

slate swan
buoyant quail
#

It's kwargs

slate swan
#

ah yes

buoyant quail
slate swan
sick birch
#

what is 1 PM + 2 PM?

slate swan
#

3PM?

sick birch
#

is that what you want in your code?

slate swan
# sick birch is that what you want in your code?

I'm not too good at explaining, I think that's what I want yes. I save a json file with an expiry date for a user, so !e user 30d, that saves the time in 30d from now, but if I run the command again !e user 15d, I want it to get the duration from the old expiry date and now, then add that to the new expiry date

sick birch
#

does !e just "bump" the expiry, actually?

slate swan
slate swan
fringe sluice
#

@slate swan Hi i ran into an issue. So when the bot kicks a user it says that it kicked x person for x reason but some some reason it looks like this:

#

kick_reason = (user," was kicked reason: ",reason) thats what i used

slate swan
fringe sluice
#

however in my cmd its correct

slate swan
#

you want to mention the user?

#

!d discord.Member.mention

unkempt canyonBOT
fringe sluice
#

and it uses user too

sick birch
fringe sluice
#

see? i don't get the jumble string

slate swan
#

what you want to display in the discord

fringe sluice
#

that

slate swan
#

the username?

fringe sluice
#

yeah

slate swan
#

:/ 1 sec

upbeat ice
fringe sluice
#

can't understand why in my cmd window it's correct

unkempt canyonBOT
#

property name```
Equivalent to [`User.name`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User.name "discord.User.name")
fringe sluice
#

they BOTH use the user

#

i'm using message author

slate swan
#

so?

#

!d discord.Message.author

unkempt canyonBOT
fringe sluice
#

yeah why is the output different in discord

#

same variable same value?

slate swan
unkempt canyonBOT
#

discord/member.py lines 367 to 374

def __str__(self) -> str:
    return str(self._user)

def __repr__(self) -> str:
    return (
        f'<Member id={self._user.id} name={self._user.name!r} global_name={self._user.global_name!r}'
        f' bot={self._user.bot} nick={self.nick!r} guild={self.guild!r}>'
    )```
fringe sluice
slate swan
#

yes

#

convert the member to str

fringe sluice
#

ok

slate swan
#

but are you sure you want that #0

sick birch
# slate swan Could you show me an example
@bot.command()
async def set_expiriation(ctx: commands.Context, days: int) -> None:
  current_expiriation: Optional[datetime] = # this comes from the database
  new_expiriation = (current_expiriation or datetime.now()) + timedelta(days=days)
  # save new_expiriation into the database
slate swan
#

you can just use member.name to get only the username

fringe sluice
#

like this kick_reason = ((str(user)," was kicked reason: ",reason)?

slate swan
#

why you make it a tuple

slate swan
sick birch
#

it only works if it's a datetime object

fringe sluice
sick birch
#

hence the typehint

slate swan
#

f"Some text {some_varriable} some other text"

#

!fstring

unkempt canyonBOT
#
Format-strings

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

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

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

fringe sluice
#

? user = str(message.author)

slate swan
#

no convert it to string only when converting to username

fringe sluice
#

oh thats number to string right?

slate swan
#

no

#

thats Member object to string

fringe sluice
#

what str() does that

fringe sluice
upbeat ice
#

username is a string?

slate swan
#

i feel like im lost

fringe sluice
slate swan
upbeat ice
slate swan
#

show your code maybe

upbeat ice
slate swan
#

hard to visualize it

buoyant quail
unkempt canyonBOT
#
Dunder methods

Double-underscore methods, or "dunder" methods, are special methods defined in a class that are invoked implicitly. Like the name suggests, they are prefixed and suffixed with dunders. You've probably already seen some, such as the __init__ dunder method, also known as the "constructor" of a class, which is implicitly invoked when you instantiate an instance of a class.

When you create a new class, there will be default dunder methods inherited from the object class. However, we can override them by redefining these methods within the new class. For example, the default __init__ method from object doesn't take any arguments, so we almost always override that to fit our needs.

Other common dunder methods to override are __str__ and __repr__. __repr__ is the developer-friendly string representation of an object - usually the syntax to recreate it - and is implicitly called on arguments passed into the repr function. __str__ is the user-friendly string representation of an object, and is called by the str function. Note here that, if not overriden, the default __str__ invokes __repr__ as a fallback.

class Foo:
    def __init__(self, value):  # constructor
        self.value = value
    def __str__(self):
        return f"This is a Foo object, with a value of {self.value}!"  # string representation
    def __repr__(self):
        return f"Foo({self.value!r})"  # way to recreate this object


bar = Foo(5)

# print also implicitly calls __str__
print(bar)  # Output: This is a Foo object, with a value of 5!

# dev-friendly representation
print(repr(bar))  # Output: Foo(5)

Another example: did you know that when you use the <left operand> + <right operand> syntax, you're implicitly calling <left operand>.__add__(<right operand>)? The same applies to other operators, and you can look at the operator built-in module documentation for more information!

fringe sluice
#

? kick_reason = ({user}, was kicked reason: ",{reason})

slate swan
#

well thats long

fringe sluice
#

without the "

slate swan
fringe sluice
#

aren't tuples a list of numbers ☠️

slate swan
#

no ..

buoyant quail
slate swan
#

but forgot about the f" ... " part

#

!fstring

unkempt canyonBOT
#
Format-strings

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

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

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

slate swan
#

look closely at the example

fringe sluice
#

works now

#

thanks

slate swan
upbeat ice
#

are you adding two datetime objects?

slate swan
#

create a converter to convert the 30d input into the timedelta object

slate swan
#

to convert from 30d?

#

that removes the d and then covnerts it to the datetime

#

so it only supports days?

#

yeah I can't even figure out this lmao

#

if its only for days just input only number

#

and dont use converter

#

I'm gonna expand it once I can figure out adding the times

#

i can show you example of such converter

upbeat ice
sick birch
#

why don't you just typehint it to int

#

that'll just be days

buoyant quail
slate swan
#

If I expand it by using your converter is it easier to add the times?

#

it returns the timedelta already

#

so you can just add it to datetime

slate swan
#

any idea what I should do? @slate swan

torn sail
#

does anyone know why my task is running many times

@tasks.loop(minutes=30)
async def update_links(self) -> None:
    print('running')
    async with aiohttp.ClientSession() as session:
        async with session.get(self.FLAGGED_LINKS_REPO_URL) as resp:
            self.flagged_links = set(await resp.json())

this prints running multiple times within the first 30 seconds

but when i remove all the aiohttp code

@tasks.loop(minutes=30)
async def update_links(self) -> None:
    print('running')

it only runs once

upbeat ice
#

where are you starting this task?

lyric echo
#

another but quicker question - someone knows if i made this good? wanted a command for sending server invites 🙂

    @commands.command()
    @commands.has_permissions()
    async def useradd(self, ctx):
      invte = await ctx.create.invite()
      await ctx.send(f"url: {invte}")
buoyant quail
#

Why you have an empty has_permissions?

vocal snow
#

And ctx.create isn't a thing, unless you added it yourself

lyric echo
#

cause was copying one command (this command was among moderation commands)

slate swan
lyric echo
#

no, like i'd like to generate discord invite and then send it as message

slate swan
#

!d discord.TextChannel.create_invite

unkempt canyonBOT
#

await create_invite(*, reason=None, max_age=0, max_uses=0, temporary=False, unique=True, target_type=None, target_user=None, target_application_id=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Creates an instant invite from a text or voice channel.

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

!d discord.ext.commands.Context.channel

unkempt canyonBOT
torn sail
torn sail
#

yeah

lyric echo
#

looks like he does, and bot is cogged

slate swan
#

!d discord.ext.commands.Cog.cog_load

unkempt canyonBOT
#

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

A special method that is called when the cog gets loaded.

Subclasses must replace this if they want special asynchronous loading behaviour. Note that the `__init__` special method does not allow asynchronous code to run inside it, thus this is helpful for setting up code that needs to be asynchronous.

New in version 2.0.
torn sail
#

oh, i thought they made it so it could be both

#

yeah it says could be but ill try it

slate swan
#

not sure though

#

could work

torn sail
#

didnt work

lyric echo
slate swan
#

using ctx.send

slate swan
lyric echo
#

like that?

    @commands.command()
    async def useradd(self, ctx):
      invte = await create.invite(*,temporary=False, unique=True)
      await ctx.send(f"url: {invte}")
upbeat ice
lyric echo
#

create invite

#

on current server or channel

slate swan
#

TextChannel have such methods

torn sail
slate swan
#

it does not appear out of nowhere

lyric echo
slate swan
#

Context is still not TextChannel

slate swan
#

thats how you get to a channel object

lyric echo
#

current text channel i mean

torn sail
slate swan
lyric echo
#
    @commands.command()
    async def useradd(self, ctx):
      invte = await ctx.channel.create.invite(*,temporary=False, unique=True)
      await ctx.send(f"url: {invte}")
slate swan
#

still a no

buoyant quail
#

bruh

lyric echo
#

then idk lol

slate swan
#

!d discord.TextChannel.create_invite

unkempt canyonBOT
#

await create_invite(*, reason=None, max_age=0, max_uses=0, temporary=False, unique=True, target_type=None, target_user=None, target_application_id=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Creates an instant invite from a text or voice channel.

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

look how the method is named

lyric echo
#

ahh, ok, now i see

slate swan
#

yeah but it still wont work

#

*,temporary=False, unique=True from where did you get this?

lyric echo
#
    @commands.command()
    async def useradd(self, ctx):
      invte = await ctx.channel.create_invite(*,temporary=False, unique=True)
      await ctx.send(f"url: {invte}")

what else to add?

lyric echo
slate swan
#

you are not supposed to copy it

lyric echo
#

ok then

slate swan
#

it just tells you what you can add

#

if you want the default values it has

#

just dont pass it

lyric echo
#

ok, but with that assign it will ever work?

slate swan
#

?

lyric echo
#

like invte = await ...

slate swan
#
Returns
The invite that was created.

Return type
Invite

lyric echo
#

more i'll test and find out xD

torn sail
# upbeat ice try using a Semaphore

huh even that didnt make a difference. i also tried asyncio.Lock() insetad of the asyncio.Semaphore(1) also

def __init__(self, bot: Bot) -> None:
    self.bot = bot
    self.flagged_links: set[str] = set()
    self.lock = asyncio.Semaphore(1)

async def cog_load(self) -> None:
    print('here')
    self.update_links.start()

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

@tasks.loop(minutes=30)
async def update_links(self) -> None:
    async with self.lock:
        print('running')
        async with aiohttp.ClientSession() as session:
            async with session.get(self.FLAGGED_LINKS_REPO_URL) as resp:
                self.flagged_links = set(await resp.json())
slate swan
#

oh you have it

slate swan
#

then whats wrong with it

upbeat ice
#

its triggering the task multiple times on startup

slate swan
#

how so

#

the cog should be loaded only once

upbeat ice
#

yeah that i dont really understand

slate swan
#

how about you add print("something") in the __init__

#

and see how many times it prints

torn sail
#

sure

slate swan
#

so the task is registered once as well

#

how you know there is more running at the same time

#

what's the typehint for member or role

torn sail
slate swan
#
user: Union[discord.Member, discord.Role]
#

how about you dont use the lock

torn sail
upbeat ice
#

well the lock was my idea

slate swan
slate swan
#

sure then

#

will work too

torn sail
#

coould be something witht await resp.json() because the task is getting stuck here probably because the github file im trying to download is 540 kb

lyric echo
#

sorry for asking yet more but someone have idea to fix that thing?

  File "/home/runner/Tux-bot-cogged-update-as-of-8122/cmds/moderation.py", line 8
    muted = (view_channel=False)
                         ^
SyntaxError: invalid syntax

its after this question earlier about refactoring role command (to split permissions from long lists of such )...

potent spear
lyric echo
#

ok

slate swan
#

perms = {"permission": True, ...}

slate swan
# torn sail coould be something witht `await resp.json()` because the task is getting stuck ...

from the docs: ```py
import asyncpg
from discord.ext import tasks, commands

class MyCog(commands.Cog):
def init(self, bot):
self.bot = bot
self.data = []
self.batch_update.add_exception_type(asyncpg.PostgresConnectionError)
self.batch_update.start()

def cog_unload(self):
    self.batch_update.cancel()

@tasks.loop(minutes=5.0)
async def batch_update(self):
    async with self.bot.pool.acquire() as con:
        # batch update here...
        pass
#

you can add exceptions

torn sail
#

lemme check that out

torn sail
#

!d discord.ext.tasks.Loop.add_exception_type

unkempt canyonBOT
#

add_exception_type(*exceptions)```
Adds exception types to be handled during the reconnect logic.

By default the exception types handled are those handled by [`discord.Client.connect()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.connect "discord.Client.connect"), which includes a lot of internet disconnection errors.

This function is useful if you’re interacting with a 3rd party library that raises its own set of exceptions.
lyric echo
#

i literally had

await member.edit(permissions=discord.Permissions(read_messages=True))

... but that cant:

execute = (read_messages=True)
await member.edit(permissions=discord.Permissions(**execute))

...

slate swan
#

then you can unpack like this

lyric echo
#

will see

torn sail
slate swan
#

👍

#

maybe you have error handler that might be silencing your exceptions

torn sail
#

i dont

#

the funny thing is that i thought the same thing but when i added a raise ValueError() in the task, it showed the error

slate swan
#

Hm

upbeat ice
#

odd

torn sail
#

oh i just checked

#

and by default discord.py silences aiohttp.ClientError

#
self._valid_exception = (
            OSError,
            discord.GatewayNotFound,
            discord.ConnectionClosed,
            aiohttp.ClientError,
            asyncio.TimeoutError,
        )
#

and if it catches these exceptions it will retry the task

#

which explains why it was running multiple times

#
                except self._valid_exception:
                    self._last_iteration_failed = True
                    if not self.reconnect:
                        raise
                    await asyncio.sleep(backoff.delay())
sharp kettle
#

Hi, can I get help not with Discord bots, but with bots on internet?

#

I want to make 10 bots that will come to one website and do some repetitive task

#

Like clicking, pressing key...

fringe sluice
#

is there a reason why this doesn't work?

role = discord.utils.get("muted")
user.add_roles(role) No error i just don't get the roll i added named muted

sharp kettle
#

I tried with Macro recorder but it doesn't really work

#

I ran two browser windows on my VM and it was quite heavy on my RAM but I need 10 not 2

fringe sluice
#

@slate swan

sharp kettle
#

My friend told me about Selenium but I don't know how to work with that

unkempt canyonBOT
#

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

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

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

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

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

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

read the docs, how is it supposed to know where to look and what to look for

#

if you have role id you can just guild.fetch_role then you can just pass the id

fringe sluice
#

i saw this on stack overflow maybe its old

slate swan
#

docs > stack

buoyant quail
#

source code > docs logo_ironpython

lyric echo
#

okay, lets go back to that server invite command...
code here:

    @commands.command(aliases=["adduser"])
    async def useradd(self, ctx):
      invte = await ctx.channel.create_invite()
      await ctx.send(f"url: {invte}")

doesnt output anything either in chat or console. like if i didnt ran command. any ideas?

lyric echo
#

current where command'd be invoked

#

if i'd type $adduser into #bots then invite would lead to #bots ... etc

fresh hatch
#

I always do ctx.channel

#

Maybe ctx.send is a thing too

#

Does the command even run? Any errors?

lyric echo
#

no it probably doesnt

#

while all rest is fine

buoyant quail
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.

This works similarly to [`send()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Messageable.send "discord.abc.Messageable.send") for non-interaction contexts.

For interaction based contexts this does one of the following...
buoyant quail
lyric echo
#

send part is fine, invite part is broken so it doesnt continue and i know it, idk just where exactly

#

i have lots of send things in code and all works

buoyant quail
#

what do you get when you run that command

lyric echo
#

nothing

#

either in terminal or in channel

#

just nothing as if i didnt typed it

buoyant quail
#

Is that command loaded?

#

It's in cog?

lyric echo
#

yep, i restarted server few times and is in cog

#

in same file commands are working

#

its 100% thing with invite

iron cosmos
#

Hello,
I've been trying for some time now to create a role allocation via a select menu for my discord bot (cog). My problem is none of the bot host supports DiscordComponents, Select, SelectOption what I need. Who knows a solution or a host that supports this?

lyric echo
# lyric echo its 100% thing with invite

btw - i went back with that code :

    @commands.command(aliases=["adduser"])
    async def useradd(self, ctx):
      invte = await ctx.create_invite()
      await ctx.send(f"url: {invte.url}")

although code with ctx.channel wasnt working too

buoyant quail
slate swan
#

discord.py has support for that built in

buoyant quail
#

the command is fine

lyric echo
#

then what?

buoyant quail
#

¯_(ツ)_/¯

slate swan
lyric echo
buoyant quail
#

You say other commands are working?

#

I'd believe they are not

lyric echo
#

means - didnt checked after refactor too much but something was working

iron cosmos
buoyant quail
lyric echo
#

WELL... forgot if i ever had it lol, i wasnt touching that bot for a year

#

edit:

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

was at top, so probably it shouldnt be an issue

#

or i should move command one tab left..

slate swan
#

if I typehint user: Union[discord.Member, discord.Role] how would I check if the mentioned was a user or member?

buoyant quail
#

!d isinstance

unkempt canyonBOT
#

isinstance(object, classinfo)```
Return `True` if the *object* argument is an instance of the *classinfo* argument, or of a (direct, indirect, or [virtual](https://docs.python.org/3/glossary.html#term-abstract-base-class)) subclass thereof. If *object* is not an object of the given type, the function always returns `False`. If *classinfo* is a tuple of type objects (or recursively, other such tuples) or a [Union Type](https://docs.python.org/3/library/stdtypes.html#types-union) of multiple types, return `True` if *object* is an instance of any of the types. If *classinfo* is not a type or tuple of types and such tuples, a [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError "TypeError") exception is raised. [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError "TypeError") may not be raised for an invalid type if an earlier check succeeds.

Changed in version 3.10: *classinfo* can be a [Union Type](https://docs.python.org/3/library/stdtypes.html#types-union).
slate swan
#
if isinstance(user, discord.Member):
    # menitoned member
#

yes

lyric echo
#

probably last question today. i have that code for automod but it doesnt catch swears if first or last word:

with open("bad-words.txt", 'r') as f:
    global badwords
    words = f.read()
    badwords = words.splitlines()

@bot.listen("on_message")
async def swears(ctx):
    msg = ctx.content.lower()
    for word in badwords:
        if word in msg:
            await ctx.delete()

any ideas?

#

means - i added spaces in this file with world list but i'd like to know how to see words automatically and to separate words by space (exact words, not word-in-middle of another..)

slate swan
#

!d discord.on_message

unkempt canyonBOT
#

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

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

Warning

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

on_message doesnt get ctx

#

it gets message

lyric echo
#

like if in word list i'd have that: apple, pear, grape
and i'd like to filter out apple but NOT pineapple
but also i'd be able to catch first, last words and words without spaces around
(pineapple not filtered but pine.apple already yep)

ctx part is fine, i talk more about regex now

slate swan
lyric echo
#

its not about it, i dont care about code quality but working functions

#

plus - i dont want to swear right here (i dont want ban xD)

slate swan
#

readability speeds up productivity Shrugdge

buoyant quail
#

!e

import re

s = "apple, pear, grape;IDK   !!! fmdskmk34534 hey .. mhmhm"
print(re.findall(r"[a-zA-Z]+", s))
unkempt canyonBOT
#

@buoyant quail :white_check_mark: Your 3.11 eval job has completed with return code 0.

['apple', 'pear', 'grape', 'IDK', 'fmdskmk', 'hey', 'mhmhm']
lyric echo
#

ok, thx

slate swan
#

@slate swan How do I get the members from a role again

sick birch
unkempt canyonBOT
slate swan
#

what type is returned?

potent spear
#

a list of member objects

#

the bot responded with a link for a reason 👀

lone lichen
potent spear
#

you're reinventing the wheel here,
discord has a built-in setting for swear words, or blacklisted words, don't try to recreate it, because people will ofc be smarter and find workarounds for your "swear words detection system"
example
you blacklist "apple", people start typing @pple or appl3 or appIe (this is uppercase i)
... 🤷‍♂️

lone lichen
#

I feel like for every new feature discord adds public bots become more useless.

potent spear
#

that's good news, it makes managing servers for non-devs very user-friendly
you shouldn't depend on third party bots all the time

#

because if it breaks, you're screwed because you have no control over it

slate swan
#

can I call len on role.members to get the total amount of users with a role?

#

!d discord.app_commands.checks.has_role

unkempt canyonBOT
#

@discord.app_commands.checks.has_role(item, /)```
A [`check()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.check "discord.app_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.

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

New in version 2.0...
slate swan
#

How do I get the snowflake ID?

buoyant quail
#

Or just the name

slate swan
#

Does discord.utils.get with ctx.guild.roles as the iterable accept role ID?

buoyant quail
#

it accepts any attribute

#

but why not just

#

!d discord.Guild.get_role

unkempt canyonBOT
#

get_role(role_id, /)```
Returns a role with the given ID.

Changed in version 2.0: `role_id` parameter is now positional-only.
buoyant quail
#

huh

unkempt canyonBOT
#

discord/utils.py lines 484 to 486

# global -> local
_all = all
attrget = attrgetter```
slate swan
#

2023-08-30 16:01:49 is there a way to convert this to discord timestamp like <t:1693436509:F>

#

I know you could convert it to an epoch but isn't there a built in method?

slate swan
#

what fields are timestamps useable in?

upbeat ice
#

of embeds?

#

if so it is Title, Descriptions and Field Name/Field Value

slate swan
#

What would be best to constantly check dates from a file? should I setup a task?

upbeat gust
slate swan
upbeat gust
slate swan
upbeat gust
slate swan
# upbeat gust Go to the discord.py server (.gg/dpy), go to a bot channel and type `?tag future...
@tasks.loop()
async def yourtask():
  # if you don't care about keeping records of old tasks, remove this WHERE and change the UPDATE to DELETE
  next_task = await db_conn.fetchrow('SELECT * FROM tasks WHERE NOT completed ORDER BY end_time LIMIT 1')
  # if no remaining tasks, stop the loop
  if next_task is None:
    yourtask.stop()

  # sleep until the task should be done
  await discord.utils.sleep_until(next_task['end_time'])

  # do your task stuff here with `next_task`

  # UPDATE the task to mark it completed, or DELETE it
  await db_conn.execute('UPDATE tasks SET completed = true WHERE row_id = $1', next_task['row_id'])

# add a `before_loop` and `wait_until_ready` if you need the bot to be logged in
yourtask.start()

# in a command that adds new task in db
if yourtask.is_running():
  yourtask.restart()
else:
  yourtask.start()
upbeat gust
#

Yeah thats wha tyou would use

torn solar
#

!paste

unkempt canyonBOT
#
Pasting large amounts of code

If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/

After pasting your code, save it by clicking the Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.

slate swan
hushed galleon
buoyant quail
#

Ahh,, in the loop

slate swan
buoyant quail
#

ye