#discord-bots

1 messages · Page 663 of 1

polar ice
#

Hey any idea what im doing wrong here?

Ignoring exception in on_button_click
Traceback (most recent call last):
  File "C:\Users\Jorda\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\discord\client.py", line 343, in _run_event
    await coro(*args, **kwargs)
  File "C:\Users\Jorda\PycharmProjects\Ticket Support Bot\ticketsystem_with_buttons_working.py", line 300, in on_button_click
    await log_ticket_history(interaction.guild,interaction.channel, interaction.author)
  File "C:\Users\Jorda\PycharmProjects\Ticket Support Bot\ticketsystem_with_buttons_working.py", line 322, in log_ticket_history
    for msg in ticket_channel.history(limit=None):
TypeError: 'HistoryIterator' object is not iterable
async def log_ticket_history(guild,ticket_channel,author):
    date = datetime.now()
    date = date.strftime('%d.%m.%y')

    db = await connect_to_sql_db('BanditBot')
    async with db.cursor() as cursor:
        await cursor.execute(f"INSERT INTO message_history (guild_id, channel_name, channel_id, author_id, date) VALUES ('{guild.id}','{ticket_channel.name}','{ticket_channel.id}','{author.id}','{date}')")
        await db.commit()

    for msg in ticket_channel.history(limit=None):
        await cursor.execute(f"UPDATE message_history WHERE channel_id = {ticket_channel.id}, SET chat_history = {msg.clean_content}")
        await db.commit()
        db.close()```

Ive been made aware not to use f-strings in SQL Query's my plan is to get this fixed then go through my entire code and fix it my bad 😄
loud junco
#

for msg in ticket_channel.history(limit=None): <---this is the line with error
TypeError: 'HistoryIterator' object is not iterable <-----this is the error

#

Is iterator iterable Python?

An iterator is an object that implements the iter method which returns itself and the next method which returns the next element. Iterators are also iterables. However, they're iterables that become exhausted while iterables will never exhausted.

#

not sure if this helps u

#

@polar ice

polar ice
#

@loud junco Reading that is like a toungue twister for my brain, thanks though 🙂

loud junco
#
date = date.strftime('%d.%m.%y')
```is this correct?
slate swan
#

from discord_components import DiscordComponents, Button, ButtonStyle

  responce = await bot.wait_for('button_click', check = lambda message: message.author == ctx.author)
  if responce.component.label == 'no':
    return

why is not work?

loud junco
#

where is all those pros

slate swan
verbal cairn
loud junco
verbal cairn
#

but that also looks correct

loud junco
#

i mean there are tons here

#

but idk where are them rn

loud junco
#
('%d.%m.%y')
#

with the ' '

verbal cairn
#

yes

loud junco
#

oo

loud junco
#

wait for those pros

#

it will take some time

verbal cairn
sick birch
#

Also consider using discord.py's native button/select menu library, it's much more intuitive imo

verbal cairn
#

I mean ur checking if the person clicking is the one using the command but still

sick birch
#

also if the library is worth its salt, then on_button_click would probably return an interaction instance, not a message

loud junco
#

i have tons of this cooldown on different commands

#
@bot.command(name='ping')
@commands.cooldown(1, 1, commands.BucketType.user)


@bot.command(name='hunt')
@commands.cooldown(1, 60, commands.BucketType.user)
#

how do i show them?

slate swan
loud junco
#

i mean

#

how do i show hunt cooldown

#

in another command

#

when i type 'rpm cooldown'
i wanna the bot to show

hunt: {huntcooldown}

polar ice
#

Hey any idea what im doing wrong here?

Ignoring exception in on_button_click
Traceback (most recent call last):
  File "C:\Users\Jorda\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\discord\client.py", line 343, in _run_event
    await coro(*args, **kwargs)
  File "C:\Users\Jorda\PycharmProjects\Ticket Support Bot\ticketsystem_with_buttons_working.py", line 300, in on_button_click
    await log_ticket_history(interaction.guild,interaction.channel, interaction.author)
  File "C:\Users\Jorda\PycharmProjects\Ticket Support Bot\ticketsystem_with_buttons_working.py", line 322, in log_ticket_history
    for msg in ticket_channel.history(limit=None):
TypeError: 'HistoryIterator' object is not iterable
async def log_ticket_history(guild,ticket_channel,author):
    date = datetime.now()
    date = date.strftime('%d.%m.%y')

    db = await connect_to_sql_db('BanditBot')
    async with db.cursor() as cursor:
        await cursor.execute(f"INSERT INTO message_history (guild_id, channel_name, channel_id, author_id, date) VALUES ('{guild.id}','{ticket_channel.name}','{ticket_channel.id}','{author.id}','{date}')")
        await db.commit()

    for msg in ticket_channel.history(limit=None):
        await cursor.execute(f"UPDATE message_history WHERE channel_id = {ticket_channel.id}, SET chat_history = {msg.clean_content}")
        await db.commit()
        db.close()```

Ive been made aware not to use f-strings in SQL Query's my plan is to get this fixed then go through my entire code and fix it my bad 😄
pliant gulch
#

Not a regular for

loud junco
#

:D

#

i have tons of this cooldown on different commands

@bot.command(name='ping')
@commands.cooldown(1, 1, commands.BucketType.user)


@bot.command(name='hunt')
@commands.cooldown(1, 60, commands.BucketType.user)
 ```how do i show them?
#

when i type 'rpm cooldown'
rpm is the syntax
i wanna the bot to show

hunt: {huntcooldown}

#

;-;

limber cosmos
#

Best way to query a local DB file every 5 minutes? I was looking into the schedule library however struggling how to implement it in my bot. The example on from the library page has a while True loop but every time I try to put that in, my bot gets stuck there and doesn't take commands.

unkempt canyonBOT
#

discord.ext.tasks.loop(*, seconds=..., minutes=..., hours=..., time=..., count=None, reconnect=True, loop=...)```
A decorator that schedules a task in the background for you with optional reconnect logic. The decorator returns a [`Loop`](https://discordpy.readthedocs.io/en/master/ext/tasks/index.html#discord.ext.tasks.Loop "discord.ext.tasks.Loop").
slate swan
#

!d asyncio.create_task or this

unkempt canyonBOT
#

asyncio.create_task(coro, *, name=None)```
Wrap the *coro* [coroutine](https://docs.python.org/3/library/asyncio-task.html#coroutine) into a [`Task`](https://docs.python.org/3/library/asyncio-task.html#asyncio.Task "asyncio.Task") and schedule its execution. Return the Task object.

If *name* is not `None`, it is set as the name of the task using [`Task.set_name()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.Task.set_name "asyncio.Task.set_name").

The task is executed in the loop returned by [`get_running_loop()`](https://docs.python.org/3/library/asyncio-eventloop.html#asyncio.get_running_loop "asyncio.get_running_loop"), [`RuntimeError`](https://docs.python.org/3/library/exceptions.html#RuntimeError "RuntimeError") is raised if there is no running loop in current thread.

This function has been **added in Python 3.7**. Prior to Python 3.7, the low-level [`asyncio.ensure_future()`](https://docs.python.org/3/library/asyncio-future.html#asyncio.ensure_future "asyncio.ensure_future") function can be used instead...
limber cosmos
slate swan
loud junco
#

:/

#

im back

#

after getting banned for me doing dumb thing

candid fractal
#

can someone help me with my homework please i am really confused

loud junco
#

ok

#

send it here :D

#

:/

#

@candid fractal send it

#

=.=

spring flax
#

Keep this in mind though

#

!rule 8

unkempt canyonBOT
#

8. Do not help with ongoing exams. When helping with homework, help people learn how to do the assignment without doing it for them.

fringe harness
#

Is there anyone down to work on a collaborative discord bot

#

I will send you details in dms

sick birch
fringe harness
#

then what is

sick birch
#

I don't know but not this

fringe harness
#

very helpful

quaint epoch
#

how do i check if a member object only recieves dm's from friends?

#

because i want to dm certain members but sometimes it returns http exeption code 400 because certain members do not take dm's from everyone

quaint epoch
worldly bane
quaint epoch
#

i tried to except discord.errors.HTTPException: but it still returned an error

sick birch
#

sometimes errors are wrapped inside a commands.CommandError iirc

#

you have to get the .original maybe that's the case here?

graceful mulch
#

Traceback (most recent call last): File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 343, in _run_event await coro(*args, **kwargs) File "main.py", line 685, in on_member_remove await channel.send(member.mention + " is no longer here") AttributeError: 'NoneType' object has no attribute 'send'
It is the error I have two similar codes here is the leave code


#member removed        
@client.event
async def on_member_remove(member):
    if member.guild.id == 912569937116147772:
        channel = client.get_channel(912569937833365596)
    elif member.guild.id == 898850971776593930:
        channel = client.get_channel(898850971818528773)
    else:
        channel = discord.utils.get(member.guild.channels, name="welcome")

    await channel.send(member.mention + " is no longer here")
    em = discord.Embed(
        title="Bye!!!",
        description="Hope you enjoyed your stay " + member.name,
        color=discord.Color(value=re[8]),
    )
    em.set_thumbnail(
        url="https://thumbs.dreamstime.com/b/bye-bye-man-says-45256525.jpg"
    )
    await channel.send(embed=em)
slate swan
#

There's no channel named "welcome"

boreal ravine
#

use f-strings

#

concatenation looks bad

slate swan
#

If I wanted to make a notification bot, would there be a way to just take the user's profile name on the platform they want notifications for or do I need their access token and such?

sick birch
boreal ravine
#

917529224552788080 sus account

sick birch
#

But most likely you'd have to connect to their API and listen for notifications

lament mesa
slate swan
#

Like if I making a bot to post a message in the server every time person x posts a new video on say TikTok, is there a way I can just take person x's TikTok username and make it so the bot can recognize when a new post is made or do I need to take person x's tokens and such.

#

Cause I am on the TikTok Developer API stuff and this is my first bot so I am not so sure what I should be looking for.

sick birch
#

Well we can't really help with the TikTok Developer API here, as I'm not sure if anyone here has used it or not

slate swan
#

I assume I need the oauth access token though right.

sick birch
#

Most likely

graceful mulch
loud junco
#

i have tons of this cooldown on different commands

@bot.command(name='ping')
@commands.cooldown(1, 1, commands.BucketType.user)


@bot.command(name='hunt')
@commands.cooldown(1, 60, commands.BucketType.user)
``` when i type 'rpm cooldown'
rpm is the syntax
i wanna the bot to show

hunt: {huntcooldown}
how do i show them?
loud junco
#

no error

upbeat otter
#

!d discord.ext.commands.CommandOnCooldown

unkempt canyonBOT
#

exception discord.ext.commands.CommandOnCooldown(cooldown, retry_after, type)```
Exception raised when the command being invoked is on cooldown.

This inherits from [`CommandError`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CommandError "discord.ext.commands.CommandError")
loud junco
#

oo

upbeat otter
#

,-,

graceful mulch
#

he means adda errro handler

#

like

loud junco
#

i mean when i type rpm cooldown

graceful mulch
#

if instance == Commands.on.Cooldown smething like this

loud junco
#

it will show all the cooldown

graceful mulch
#

Idk

upbeat otter
loud junco
#

:D

upbeat otter
#

Type them out lol

loud junco
#

=.=

#

whats the variable

#

cuz the time will keep changing

upbeat otter
#

,-, wdym

loud junco
#

the hunt cd is 1 min

upbeat otter
loud junco
#

i hunted now

#

after 30 secs i type rpm cd

#

i want it to show hunt: 40 secs

#

u get what i mean?

upbeat otter
#

Just run the command again ,-,

loud junco
#

?

upbeat otter
#

Nvm, i didnt understand best of luck

loud junco
#

:/

#

i wanna make a command call rpm cd

#

it will show all the cooldown

upbeat otter
#

Nice

loud junco
#

but idk how

#

=.=

upbeat otter
#

Me too ,-,

loud junco
#

where is those pros

slate swan
#

How to host discord bot on rdp?

slate swan
loud junco
slate swan
#

Vps

loud junco
#

nvr heard of it

#

grinch is here :D

maiden fable
maiden fable
unkempt canyonBOT
#

exception discord.ext.commands.CommandOnCooldown(cooldown, retry_after, type)```
Exception raised when the command being invoked is on cooldown.

This inherits from [`CommandError`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CommandError "discord.ext.commands.CommandError")
loud junco
#

i mean

maiden fable
#

!d discord.ext.commands.CommandOnCooldown.retry_after

unkempt canyonBOT
loud junco
#

i wanna make a command to show them

maiden fable
slate swan
maiden fable
#

@slate swan open a command prompt, cd yo the current directory and then run python main.py

slate swan
maiden fable
slate swan
#

Already Install

maiden fable
unkempt canyonBOT
maiden fable
#

!windows-path

unkempt canyonBOT
#

PATH on Windows

If you have installed Python but forgot to check the Add Python to PATH option during the installation, you may still be able to access your installation with ease.

If you did not uncheck the option to install the py launcher, then you'll instead have a py command which can be used in the same way. If you want to be able to access your Python installation via the python command, then your best option is to re-install Python (remembering to tick the Add Python to PATH checkbox).

You can pass any options to the Python interpreter, e.g. to install the [numpy](https://pypi.org/project/numpy/) module from PyPI you can run py -3 -m pip install numpy or python -m pip install numpy.

You can also access different versions of Python using the version flag of the py command, like so:

C:\Users\Username> py -3.7
... Python 3.7 starts ...
C:\Users\Username> py -3.6
... Python 3.6 starts ...
C:\Users\Username> py -2
... Python 2 (any version installed) starts ...
slate swan
#

Which path?@maiden fable

#

not that

maiden fable
#

Read the embed above

slate swan
#

Uninstalling it and reinstalling it

#

Wait

#

make sure you check the "add to path"

boreal ravine
#

whch one should I use?

class View(discord.ui.View):
  ...

async def ping(ctx): #option A
  await ctx.send('ping', view=View())

async def ping(ctx): #option B
  view = View()
  await ctx.send('ping', view=view)

is using the class itself better or is creating an instance of it better

maiden fable
#

First

boreal ravine
#

hm

maiden fable
#

Ah wait nvm

#

Second one, I misunderstood

boreal ravine
#

o

#

so I should use the second one?

slate swan
#

Does it even matter?

boreal ravine
#

i have no idea, just asking for suggestions since I thought using instances would be better

slate swan
#

Well you probably want to use view.wait() later, so you know the answer.

loud junco
#

where do i put the hunt

#

in get_cooldown_retry_after(ctx)

slate swan
slate swan
loud junco
#

i dont wanna loop

#

i just need a few

#

instead of all of them

slate swan
#

get the command objects first , then use the function on them

#

!d discord.ext.commands.Bot.get_command

unkempt canyonBOT
#

get_command(name)```
Get a [`Command`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command") from the internal list of commands.

This could also be used as a way to get aliases.

The name could be fully qualified (e.g. `'foo bar'`) will get the subcommand `bar` of the group command `foo`. If a subcommand is not found then `None` is returned just as usual.
slate swan
#

you can enter command name as a string as the name arg

loud junco
#

get_command('hunt')
like this?

#

or without ' '

graceful mulch
#

TypeError: 'module' object is not callable

#

What to do know

#

ignore this error

#

Solved myself

loud junco
#

name = bot.getcommand('hunt)
name.get_cooldown_retry_after(ctx)

loud junco
maiden fable
loud junco
#

like this?

prisma spoke
#

how can i search for a specific line from the pinned msg of the channel?

sullen shoal
#

creating an instance is useful when you want to pass the sent message to your view,

view = View()
view.message = ctx.send(..., view=view)```
#

and setting the current embed as well

loud junco
#

from discord.ext import commands
import discord.ext.commands

#

i got these 2 imported

sullen shoal
#

!d discord.ext.commands.Bot.get_command

unkempt canyonBOT
#

get_command(name)```
Get a [`Command`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command") from the internal list of commands.

This could also be used as a way to get aliases.

The name could be fully qualified (e.g. `'foo bar'`) will get the subcommand `bar` of the group command `foo`. If a subcommand is not found then `None` is returned just as usual.
sullen shoal
#

snake case

#

!pep8

unkempt canyonBOT
#

PEP 8 is the official style guide for Python. It includes comprehensive guidelines for code formatting, variable naming, and making your code easy to read. Professional Python developers are usually required to follow the guidelines, and will often use code-linters like flake8 to verify that the code they're writing complies with the style guide.

More information:
PEP 8 document
Our PEP 8 song! :notes:

loud junco
#

oo

#

_

sullen shoal
#

a_good_lib_will_always_name_attributes_and_methods_like_this

#

python_lib_ofc

maiden fable
prisma spoke
#

how to search for a specific line from the pinned msg of a channel?

#

the msg wud be written is written by the bot but content is given by the user

maiden fable
#

!d discord.TextChannel.pins

unkempt canyonBOT
#

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

Retrieves all messages that are currently pinned in the channel.

Note

Due to a limitation with the Discord API, the [`Message`](https://discordpy.readthedocs.io/en/master/api.html#discord.Message "discord.Message") objects returned by this method do not contain complete [`Message.reactions`](https://discordpy.readthedocs.io/en/master/api.html#discord.Message.reactions "discord.Message.reactions") data.
loud junco
prisma spoke
maiden fable
#

Just use a for loop then

prisma spoke
#

how can i loop thro the contents?

sullen shoal
#

so you basically want to search for a specific line from text

sick birch
#

!e

myString = "This is a string."
print("string" in myString)
unkempt canyonBOT
#

@sick birch :white_check_mark: Your eval job has completed with return code 0.

True
sick birch
#

that works for searching through a string

sullen shoal
#

!d str.splitlines

unkempt canyonBOT
#

str.splitlines([keepends])```
Return a list of the lines in the string, breaking at line boundaries. Line breaks are not included in the resulting list unless *keepends* is given and true.

This method splits on the following line boundaries. In particular, the boundaries are a superset of [universal newlines](https://docs.python.org/3/glossary.html#term-universal-newlines)...
sullen shoal
#

you can use enumerate to get the index of the current line if iterating

prisma spoke
prisma spoke
slate swan
# unkempt canyon

Returns a list of messages. Iterate through it, and check the .content attribute of the currently iterated element and compare it with your other string.

slate swan
#

It's a basic for loop

prisma spoke
#

.content one

sick birch
slate swan
prisma spoke
prisma spoke
weary obsidian
#

pls help me..im trying to code discord bot in spyder.... can anyone guide me ? pls

maiden fable
#

What u need help with

weary obsidian
maiden fable
upbeat otter
#

how do I read messages in a channel?

maiden fable
#

on_message?

upbeat otter
maiden fable
#

!d discord.Permissions.read_message_history

unkempt canyonBOT
weary obsidian
upbeat otter
#

thankuu

maiden fable
#

(:

upbeat otter
#

permissions ,-,

weary obsidian
maiden fable
upbeat otter
maiden fable
#

Hahaha

#

It was a wild guess 🤷‍♂️

upbeat otter
#

i got it ,-,

#

stackflow

weary obsidian
maiden fable
#

Oh hmm

maiden fable
sick birch
#

pretty sure it's just discord

slate swan
#

It isn't.

sick birch
#

oh alright been a while since i installed

placid skiff
weary obsidian
slate swan
#

Used to be, now it's an outdated version.

sick birch
#

i see

prisma spoke
maiden fable
sick birch
slate swan
sick birch
#

mm

placid skiff
slate swan
#

Syntax is not the same as command not found.

sick birch
#

yeah i can't really assist with python installation on windows, i've only ever done it on linux sorry haha

slate swan
#

You don't get a syntax error in the cmd.

prisma spoke
sick birch
placid skiff
#

Change the token 😂

weary obsidian
#

done

#

ty for telling

sick birch
#

👍

prisma spoke
graceful mulch
#

a!bot

maiden fable
#

The token do be nice tho ngl

sick birch
prisma spoke
slate swan
#
bla = await ...pins()
for m in bla:
prisma spoke
slate swan
#

No

#

m.content

#

Since m will be your element

prisma spoke
slate swan
#

Come on...

#

This is like beginner level for loop

#
bla = await ...pins()
for m in bla:
    print(m.content) # Will print the message content
prisma spoke
#

taking c as channel id
m = await c.channel.pins()

#

channel object has pin attribute

prisma spoke
#

in await .. pins

sick birch
#

this is not that hard, get the pins, loop through, find what you need

slate swan
#

You're iterating through a list

#

m will be each element in that list

prisma spoke
#

ahh u didnt get what m sayng

slate swan
#

One by one

prisma spoke
#

nvm

slate swan
#

So each pinned message one by one

sick birch
#

you can break the loop when you find what you need

slate swan
#

So m.content will give the content of the current message you're iterating through

slate swan
#

as in message.channel or ctx.channel

prisma spoke
#

ohk thx

slate swan
#

m will be a message object

#

... is the channel that's right

#

So it can be message.channel, msg.channel, ctx.message.channel, or any custom variable

prisma spoke
#

alr thx a lot

tawdry perch
loud junco
#

how do i set rpm p and rpm profile do the same thing

#

i need to do 2 different command?

prisma spoke
#
        tourney_type = msg.content
        message = await c.send(f"Type:-\n{tourney_type}")
        await message.pin(message)```
command raised an exception Message.pin takes one positional argument but 2 were given
tacit horizon
#

why my discord @client.command not working if i put @client.event after that

tacit horizon
#

ok wait

dusky pine
#

so it's just await message.pin()

tacit horizon
#
async def meme(ctx):
    async with aiohttp.ClientSession() as cs:
        async with cs.get("https://www.reddit.com/r/memes.json") as r:
            memes = await r.json()
            embed = discord.Embed(
                color = discord.Color.purple()
            )
            embed.set_image(url=memes["data"]["children"][random.randint(0,25)]["data"]["url"])
            embed.set_footer(text=f"{ctx.author}")
            await ctx.send(embed=embed)
                

@client.event
async def on_message(message):
    if message.author == client.user:
        return
    if message.content.startswith('test'):
        await message.channel.send('working.....')  
        print('how')```
#

the message working

dusky pine
slate swan
#

i have a question how to make xp showin in the rank command i mean when sameone types +rank it need shows current rank of user and exp what he gots and he needs to get to another level but i dont know how to make it and i done this so far ```with open("users.json", "ab+") as ab:
ab.close()
f = open('users.json','r+')
f.readline()
if os.stat("users.json").st_size == 0:
f.write("{}")
f.close()
else:
pass

with open('users.json', 'r') as f:
users = json.load(f)
@bot.event
async def on_message(message):
if message.author.bot == False:
with open('users.json', 'r') as f:
users = json.load(f)
await add_experience(users, message.author)
await level_up(users, message.author, message)
with open('users.json', 'w') as f:
json.dump(users, f)
await bot.process_commands(message)

async def add_experience(users, user):
if not f'{user.id}' in users:
users[f'{user.id}'] = {}
users[f'{user.id}']['experience'] = 0
users[f'{user.id}']['level'] = 0
users[f'{user.id}']['experience'] += 6
print(f"{users[f'{user.id}']['level']}")

async def level_up(users, user, message):
experience = users[f'{user.id}']["experience"]
lvl_start = users[f'{user.id}']["level"]
lvl_end = int(experience ** (1 / 4))
if lvl_start < lvl_end:
await message.channel.send(f':tada: {user.mention} zdobyłeś poziom {lvl_end}. Gratulacje :tada:')
users[f'{user.id}']["level"] = lvl_end

@bot.command()
async def rank(ctx, member: discord.Member = None):
if member == None:
userlvl = users[f'{ctx.author.id}']['level']
await ctx.send(f'{ctx.author.mention} Masz poziom{userlvl}!')
else:
userlvl2 = users[f'{member.id}']['level']
await ctx.send(f'{member.mention} Ma poziom {userlvl2}!') ```

unkempt jewel
dusky pine
unkempt jewel
shadow wraith
dusky pine
dusky pine
unkempt jewel
shadow wraith
#

oh optional argument i can learn something here

unkempt jewel
dusky pine
dusky pine
tacit horizon
#

worked

unkempt jewel
shadow wraith
dusky pine
#

nobody

shadow wraith
#

🤔

unkempt jewel
#

idk how to make the bot mentions someone

shadow wraith
#

think about that, then if you can't think. do: .hug @member

dusky pine
#

Notice the = None

#

it makes the argument a keyword argument, ie an "optional argument"

pale palm
#

Is there way to make my bot online 24/7 without sleeping?

dusky pine
pale palm
#

For free.

dusky pine
#

well, you won't be able to find good ones for free

#

but there's repl.it (with a pinger, to keep your bot alive)

pale palm
slate swan
slate swan
pale palm
dusky pine
slate swan
unkempt jewel
#

yo why my bot reply 2 times

slate swan
#

You have 2 instances running

unkempt jewel
slate swan
#

Which means you ran your bot twice, per mistake

graceful mulch
#

It comes like this a lb command with people indexed multiple time

#

what to do

dusky pine
slate swan
unkempt jewel
graceful mulch
slate swan
#

Make sure you shutdown all processes of your bot.

unkempt jewel
#

it sill 2 times

graceful mulch
#
players = {}



@client.command(aliases = ["lb"])
async def globallb(ctx,x = 10):
    users = await get_bank_data()
    leader_board = {}
    total = []
    for user in users:
        name = int(user)
        total_amount = users[user]["wallet"] + users[user]["bank"]
        leader_board[total_amount] = name
        total.append(total_amount)

    total = sorted(total,reverse=True)    

    em = discord.Embed(title = f"Top {x} Richest People" , description = "This is decided on the basis of raw money in the bank and wallet",color = discord.Color(0xfa43ee))
    index = 1
    for amt in total:
        id_ = leader_board[amt]
        member = client.get_user(id_)
        name = member
        em.add_field(name = f"{index}. {name}" , value = f"{amt}",  inline = False)
        if index == x:
            break
        else:
            index += 1

    await ctx.send(embed = em)
slate swan
#

You might have one instance running in Visual Studio Code and one in the cmd.

dusky pine
slate swan
#

Then don't have that

dusky pine
#

either kill cmd or kill vsc

slate swan
#

Run it only in Visual Studio Code or cmd.

graceful mulch
#

pls help me @slate swan

unkempt jewel
#

ok done

graceful mulch
#

Yes

#

I use it unfortunately

#

cuz I dont know mongodb or something

dusky pine
graceful mulch
#

yes

dusky pine
#

or postgresql

boreal ravine
unkempt canyonBOT
#

Hey @graceful mulch!

Uh-oh! It looks like your message got zapped by our spam filter. We currently don't allow .txt attachments, so here are some tips to help you travel safely:

• If you attempted to send a message longer than 2000 characters, try shortening your message to fit within the character limit or use a pasting service (see below)

• If you tried to show someone your code, you can use codeblocks
(run !code-blocks in #bot-commands for more information) or use a pasting service like:

https://paste.pythondiscord.com

dusky pine
graceful mulch
#

{"916636227548110849": {"900992402356043806": {"experience": 407, "level": 4}}, "912569937116147772": {"900992402356043806": {"experience": 235, "level": 3}, "917406319273730059": {"experience": 69, "level": 2}, "875542771556048936": {"experience": 3, "level": 1}}, "912559425921892392": {"900992402356043806":

dusky pine
#

this is just spamming, please stop

slate swan
#

Why'd you need to send this spam?

pale palm
#

What are you doing?

graceful mulch
slate swan
#

Can you please delete it, thanks.

dusky pine
graceful mulch
#

{"900992402356043806": {"wallet": 210984209840955598, "bank": 10231084984298421629970412847523700, "career": "Fastfood Cook", "rank": "None", "bag": [{"item": "diamondpass", "amount": 100}, {"item": "watch", "amount": 100}, {"item": "laptop", "amount": 100}, {"item": "pc", "amount": 100}, {"item": "ferrari", "amount": 100}, {"item": "kingpass", "amount": 100}, {"item": "shovel", "amount": 100}, {"item": "fishingrope", "amount": 100}, {"item": "juice", "amount": 441}]}, "748500414277877841": {"wallet": 250, "bank": 0, "career": "None", "rank": "None"}, "911849528972410940": {"wallet": 250, "bank": 0, "career": "None", "rank": "None"}, "728918313211789363": {"wallet": 250, "bank": 8324, "career": "None", "rank": "None"}, "812779224183209985": {"wallet": 250, "bank": 8324, "career": "None", "rank": "None"}, "780522171226390638": {"wallet": 32, "bank": 340198412095025, "career": "None", "rank": "None"}, "914747295382265897": {"wallet": 250, "bank": 0, "career": "None", "rank": "None"}} It is the correct one

prisma spoke
# slate swan Nothing.
        pinned_messages = await ctx.message.channel.pins()
        for message in pinned_messages:
            print(message)
            a = message.splitlines()
            print(a)```
?
prisma spoke
#

this gave an error

dusky pine
slate swan
graceful mulch
dusky pine
#

so you have to access message.content

prisma spoke
dusky pine
dusk pumice
slate swan
#

!pastebin

unkempt canyonBOT
#

Pasting large amounts of code

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

After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.

graceful mulch
#

Ok

boreal ravine
graceful mulch
#

BTW HElp meeeeeeeeeeeee

prisma spoke
slate swan
#

Try it and see

#

¯\_(ツ)_/¯

prisma spoke
boreal ravine
dusky pine
#

i've actually never used mongodb, might consider giving it a try

boreal ravine
prisma spoke
#

sqlite better

dusky pine
#

and stores itself in a file

#

which is convenient though

prisma spoke
#
            await bot.db.commit()
            await ctx.send("Done!")``` this didnt create  the tablle
#

if i remove if not exists then it shows table is there

#

but its not

slate swan
#

A space after one is required

dusky pine
#

oh my god i'm switching to mongo rn

prisma spoke
prisma spoke
#

wht happened?

dusky pine
#

IT IS AMAZING

prisma spoke
#

its json but n a db form

dusky pine
#

it is

#

that does not mean it's bad

prisma spoke
prisma spoke
dusky pine
#

mongo uses bson

slate swan
#

Mongodb's great if you don't consider it's speed

pale palm
#

What if json + mongodb.

dusky pine
prisma spoke
#

@slate swan py if msg.content == "1v1": await bot.db.execute("CREATE TABLE IF NOT EXISTS one (user_id int, uid int, member_name str , ign str, PRIMARY KEY (user_id, member_name))") await bot.db.commit() await ctx.send("Done!") still doesnt create

dusky pine
#

i guess?

pale palm
#

No, i mean. Save the data into json file and save it every 10 second.

dusky pine
dusky pine
pale palm
#

What if a hundred people use my bot.

dusky pine
prisma spoke
pale palm
#

I'll spam requests.

dusky pine
#

i'll just roll back the db if anything wrong happens

full valley
#
ggid = settings.find_one({"guild_id": ctx.guild.id})
game_id = ggid["game_id"] - 1
regions = {'USE': 0, 'USW': 0, 'EU': 0, 'AS': 0, 'ME': 0, 'OCE': 0, 'SA': 0, }
players = []
players_roles = []
USE = 731704626600214600
USW = 31704701455695963
EU = 731705390697545748
AS = 731704908272894105
ME = 731704730056917013
OCE = 731704958893949072
SA = 737460378610696203
for x in games[game_id]:
   players.append(ctx.guild.get_member(x))
for p in players:
   players_roles.append(p.roles)
for p in players_roles:
    if p.id == USE:
        regions['USE'] += 1
    if p.id == USW:
        regions['USW'] += 1
    if p.id == EU:
        regions['EU'] += 1
    if p.id == AS:
        regions['AS'] += 1
    if p.id == ME:
        regions['ME'] += 1
    if p.id == OCE:
        regions['OCE'] += 1
    if p.id == SA:
        regions['SA'] += 1
    else:
        continue
region = max(regions, key=regions.get)
print(max(regions, key=regions.get))
  File "D:\6Mans\Heps6Mans\Main\main_v10.py", line 329, in randteamchoice
    if p.roles.id == USE:
AttributeError: 'list' object has no attribute 'id'
#

Anyone know how to fix?

slate swan
dusky pine
slate swan
#
embed = discord.Embed()
embed.set_image(
    url="attachment://filename.png"
)
image = discord.File("/path/to/filename.png")
await ctx.send(
    embed=embed,
    file=image
)```
prisma spoke
dusky pine
tawdry perch
#
ext = []
for filename in os.listdir('MyBot/cogs/moderation'):
    if filename.endswith('.py'):
        ext.append(f"MyBot.cogs.moderation.{filename}")
    for filename in os.listdir('MyBot/cogs/other'):
        if filename.endswith(f"MyBot.cogs.other.{filename}"):
            ext.append(f"MyBot.cogs.{filename[:-3]}")
        for filename in os.listdir('MyBot/cogs/other/antimusic'):
            ext.append(f"MyBot.cogs.other.antimusic.{filename}")
``` Traceback when I try to load the extensions: https://paste.pythondiscord.com/wejepifafe.py
prisma spoke
#

bot.db = await aiosqlite.connect("C:\\Users\\admin\\Downloads\\tourneyusers.db")

tawdry perch
#

oh wait don't mind the if ends with statements

slate swan
#

"CREATE TABLE IF NOT EXISTS one (user_id int, uid int, member_name str , ign str, PRIMARY KEY (user_id, member_name))"

#

read the full part , you send the file object in .send() and use it's url for the embed

prisma spoke
slate swan
prisma spoke
#

it didnt work cuz i had another db also named bot.db

dusky pine
#

exactly
attachment://folder/filename.png

#

something like that, idk if it's different on windows

prisma spoke
unkempt canyonBOT
#

saving_data/sqlite3_usage.py lines 39 to 46

async with aiosqlite.connect('animals.db') as connection:
    async with connection.cursor() as cursor:
        await cursor.execute(
            '''
            CREATE TABLE IF NOT EXISTS animals
            ( user TEXT , animal TEXT)
            '''
        )```
prisma spoke
slate swan
#

check if it has cursor or not

prisma spoke
#
await bot.db.execute("CREATE TABLE IF NOT EXISTS totals (guild_id int, inviter_id int, normal int, left int, fake int, PRIMARY KEY (guild_id, inviter_id))")```
slate swan
#

weird

#

@slate swan You like my enhanced WinRar server profile? You can now set custom banner and 'About me' on each server.

prisma spoke
#

it doesnt have cursor

slate swan
#

how did you define bot.db there?

rocky mist
#

hey im stuck on ideas how to make a warn command, any ideas pls?

shadow wraith
slate swan
#

you can send multiple files , but you know , embeds can have a single image

#

@velvet tinsel You like my enhanced WinRar server profile? You can now set custom banner and 'About me' on each server.

shadow wraith
#

can ctx be used in discord.ui.button because i want to make it so whenever someone clicks the button tehy get dmed

slate swan
#

name the images according to their positions py file1 = discord.File('image.png') file2 = discord.File('thumbnail.png') embed.set_thumbnail(url= "attachment://thumbnail.png") embed.set_image(url="attachment://image.png") ...... await ....send(embed =embed , files=[file1 , file2]

tawdry perch
#

The second loop tries to load extension from MyBot/cogs/file but it's supposed to do MyBot/cogs/other/file, why? ```py
for folder in os.listdir('MyBot/cogs/moderation'):
if folder.endswith('.py'):
ext.append(f"MyBot.cogs.moderation.{folder[:-3]}")
for subfolder in os.listdir('MyBot/cogs/other'):
if subfolder.endswith('.py'):
ext.append(f"MyBot.cogs.{subfolder[:-3]}")

slate swan
tawdry perch
#

it attemp of loading a cog MyBot/cogs/bonker but it's supposed to do MyBot/cogs/other/bonker

slate swan
tawdry perch
#

oh frick

#

Another problem, it attemps to load __init__.py files as well...

shadow wraith
#

oh yeah and whenever the button is clicked how can you send like a message which only you can see and is dismisaable

slate swan
#

make a if statement to ignore __init__.py , or add py def setup(bot): pass in your __init__.py , basically what the second option do is -> nothing

boreal ravine
#

hm

#

just check if it wasnt heads/tails and then make the bot send an error message

tawdry perch
#
Extension 'MyBot.cogs.other.antimusic.kicker' raised an error: TypeError: cogs must derive from Cog
``` what does this mean
boreal ravine
#

u subclassed it wrong

tawdry perch
#

oh...

shadow wraith
slate swan
#

!d discord.Embed.set_footer takes an icon_url kwarg iirc

unkempt canyonBOT
#

set_footer(*, text=Embed.Empty, icon_url=Embed.Empty)```
Sets the footer for the embed content.

This function returns the class instance to allow for fluent-style chaining.
slate swan
#

yea

tawdry perch
#

isn't this correct ```py
class kicker(commands.Cog):
def init(self, bot):
self.bot = bot

boreal ravine
#

by checking if choice isnt heads/tails ```py
if choice not in ["heads", "tails"]:
...

boreal ravine
tawdry perch
#

?

slate swan
#

show your setup function , cyber

tawdry perch
#
def setup(bot):
    bot.add_cog(kicker(bot))
slate swan
#

thats unlikely to happen , check your commands import

#

maybe you imported it from some other library as kayle said

#

i often import it from discord instead of disnake

tawdry perch
#

aha I just did that ;-;

slate swan
#

xd

shadow wraith
#

i keep getting this error `

tawdry perch
#

I forgot that I alrd changed libs

shadow wraith
#
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/discord/ext/commands/bot.py", line 960, in invoke
    await ctx.command.invoke(ctx)
  File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/discord/ext/commands/core.py", line 825, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/discord/ext/commands/core.py", line 134, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: to_components() missing 1 required positional argument: 'self'
#

even tho i defined self in the discord.ui.button

maiden fable
#

Code

shadow wraith
#
class FakeBean(discord.ui.View):
    @discord.ui.button(style=discord.ButtonStyle.blurple, label='pay respect 🥶')
    async def payedRespect(self, button: discord.Button, interaction: discord.Interaction):
        await interaction.response.send_message("you payed respect :cold_face:", ephmeral=True)
slate swan
#

discord.ui.Button tho

shadow wraith
maiden fable
slate swan
#

ow?

maiden fable
#

It's for the deco lol

shadow wraith
#

nah i dont think so it worked with lowercase

slate swan
#

oh i see

maiden fable
#

!d discord.ui.button see

unkempt canyonBOT
#

discord.ui.button(*, label=None, custom_id=None, disabled=False, style=<ButtonStyle.secondary: 2>, emoji=None, row=None)```
A decorator that attaches a button to a component.

The function being decorated should have three parameters, `self` representing the [`discord.ui.View`](https://discordpy.readthedocs.io/en/master/api.html#discord.ui.View "discord.ui.View"), the [`discord.ui.Button`](https://discordpy.readthedocs.io/en/master/api.html#discord.ui.Button "discord.ui.Button") being pressed and the [`discord.Interaction`](https://discordpy.readthedocs.io/en/master/api.html#discord.Interaction "discord.Interaction") you receive.

Note

Buttons with a URL cannot be created with this function. Consider creating a [`Button`](https://discordpy.readthedocs.io/en/master/api.html#discord.ui.Button "discord.ui.Button") manually instead. This is because buttons with a URL do not have a callback associated with them since Discord does not do any processing with it.
shadow wraith
#

🤔

#

wait you can specify an emoji?

slate swan
#

i though they were constructing a button :p

maiden fable
shadow wraith
maiden fable
shadow wraith
#
@bot.command()
async def bean(ctx: commands.Context, member: discord.Member):
    await ctx.send(f"{member} has been beaned | `{member.id}", view=FakeBean)
maiden fable
#

Seems like a bug tbh

#

Ahhh

#

FakeBean()

shadow wraith
#

:trol:

maiden fable
#

U forgot to make an instance of it

#

Hahaha

shadow wraith
#

last time it worked without parentheses but idk what happened now

maiden fable
#

I knew that error came when u try to use an instance method on the class itself

maiden fable
#

Lmao

shadow wraith
boreal ravine
#

dont use elif, use if and add that statement at the top of your code

#

and use return, not pass

tawdry perch
#

after trying to fix my cog loader for about a day it's now working

pale palm
#

Cool.

tawdry perch
#

now I need a command to load / unload cogs...

pale palm
#

Why'd you need unload cogs command?

tawdry perch
#

in case of I'm fixing a bug/developing a new version but it does not work I can just unload it and still keep bot functional

#

wihtout the need of putting bot completely offline

pale palm
#

Oh.

tawdry perch
#

When I restarted the bot this happened ;-; ```py
raise errors.ExtensionAlreadyLoaded(name)
disnake.ext.commands.errors.ExtensionAlreadyLoaded

#

!d discord.Embed.set_footer

unkempt canyonBOT
#

set_footer(*, text=Embed.Empty, icon_url=Embed.Empty)```
Sets the footer for the embed content.

This function returns the class instance to allow for fluent-style chaining.
tawdry perch
#

hmm

#

what is info["footer"]

shadow wraith
#

ok this time its a different discord.ui class but 💀

Ignoring exception in view <CodeSystem timeout=180.0 children=3> for item <Button style=<ButtonStyle.success: 3> url=None disabled=False label='1' emoji=None row=None>:
Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/discord/ui/view.py", line 358, in _scheduled_task
    await item.callback(interaction)
  File "/Users/sadancooler/Documents/Code/Python/bots/mystery/bot.py", line 32, in firstcode
    await interaction.response.send_message("bmJnZ3E=", ephemeral=True)
AttributeError: 'Button' object has no attribute 'response'
```i dont see wuts wrong
#

oh i get whats wrong

#

i put the order different when im defining object names

boreal ravine
pale palm
tawdry perch
#

I closed the bot and ran again

pale palm
#

Sec.

tawdry perch
#
    try:
        for extension in ext:
            bot.load_extension(extension)
    except disnake.ext.commands.errors.ExtensionAlreadyLoaded:
        bot.unload_extension() #get the extension name that raised it and unload
        #reload it
``` how can I do this
patent surge
#

How do I make Category and add channels to it ?

maiden fable
#

!d discord.Guild.create_category_channel

unkempt canyonBOT
#

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

Same as [`create_text_channel()`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild.create_text_channel "discord.Guild.create_text_channel") except makes a [`CategoryChannel`](https://discordpy.readthedocs.io/en/master/api.html#discord.CategoryChannel "discord.CategoryChannel") instead.

Note

The `category` parameter is not supported in this function since categories cannot have categories.
placid skiff
#

usually the ExtensionAlreadyLoaded should never happen, i suggest you to do something like this:

from glob import glob

COGS = [path.split("\\")[1][:-3] for path in glob("*yourpathtocogs*/cogs/*py")]

# In your code, the block where you load cogs
        for cog in COGS:
            try:
                print(f"    loadin {cog}")
                self.load_extension(f"lib.cogs.{cog}")
            except NoEntryPointError:
                print(f"    failed to load {cog}\nNo setup found")
            except ExtensionFailed:
                print(f"    failed to load {cog}\nThe extension or its setup had an execution error")
            else:
                print(f"    {cog} loaded")

The NoEntryPointError and ExtensionFailed error are the only two possible errors that can occur when you first load the cogs, the NoEntryPointError occurs when you didn't declare the setup in your cog, the ExtensionFailed occurs when the cogs has an internal error

slate swan
#

so i have a discord bot with a command which updates a json file and the bot is being hosted in heroku and the files are in my github repo even after users using the command the json file isnt getting updated in my github repository

placid skiff
# tawdry perch What about handling this?

the ExtensionAlreadyLoaded occurs when you try to load an extension that is already loaded. You have no need to unload the extension because when the error occurs it stop the execution and don't load the cog

maiden fable
unkempt canyonBOT
#

exception discord.ext.commands.ExtensionAlreadyLoaded(name)```
An exception raised when an extension has already been loaded.

This inherits from [`ExtensionError`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.ExtensionError "discord.ext.commands.ExtensionError")
maiden fable
#

The name attr

tawdry perch
#

Hmm how do I avoid that error

maiden fable
#

Try except?

tawdry perch
#

I restarted my bot and waited for it to shutdown

#

I will try

slate swan
#

how to make a bot dm a user

maiden fable
maiden fable
#

Yea

slate swan
#

do you need to use id in get_user()

slate swan
maiden fable
#

Yea

maiden fable
slate swan
#

Ignoring exception in command dm:
Traceback (most recent call last):
File "C:\Users\ADMIN\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\discord\ext\commands\core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "C:\Users\ADMIN\DeltaDiscordBot\main.py", line 135, in dm
user = bot.get_user(521325126722125874)
NameError: name 'bot' is not defined
`
The above exception was the direct cause of the following exception:

Traceback (most recent call last):
File "C:\Users\ADMIN\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\discord\ext\commands\bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\ADMIN\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\discord\ext\commands\core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\ADMIN\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\discord\ext\commands\core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: NameError: name 'bot' is not defined`

pale palm
slate swan
#

ok ty

slate swan
#

Guys where can I enable intents.invite

maiden fable
slate swan
#

normally?

#

intents.invite=True

royal lichen
slate swan
#

ok thx

slate swan
royal lichen
#

Yes

slate swan
#

thx

valid galleon
#

so im using a sqlite db to count the number of messages a user has sent in a server, and the way it does that is when a user sends a message(checked with on_message), it connects to the database, and increments the value by one. but the message counts keep resetting, and a lot of users' data keeps getting deleted? any idea why this happens?

tawdry perch
#

Where do you host your bot?

tawdry perch
valid galleon
#

oh

#

its heroku, isnt it?

#

which is causing the error

tawdry perch
#

Do you restart the bot usually?

royal lichen
#

Heroku environments - and thus files - are deleted when the bot's environment restarts

valid galleon
tawdry perch
#

The files wont stay saved the database resets everytime

#

use a server based db

royal lichen
tawdry perch
valid galleon
#

do other free hosting services like epikhost, etc support slite?

#

sqlite*

tawdry perch
#

epikhost does not suppot sqlite

valid galleon
#

well that sucks

tawdry perch
#

I would recommend server based db instead

valid galleon
#

is there any such db with almost the same syntax as sqlite3?

tawdry perch
#

MySQL might be and postgres as they are SQL dbs

royal lichen
#

Likely none will have the exact same syntax, but databases like PostgreSQL use very similar SQL

tawdry perch
#

SQLite is a lite version of database as the name says so, and PostgreSQL will have a lot more features than SQLite. Same thing might be for MySQL. So you will have to learn the database you choice again (I might be wrong)

royal lichen
#

If you use a module like databases you can use the same interface to use sqlite locally, and postgres or mysql when running the bot for real

#

!pypi databases

unkempt canyonBOT
junior verge
#

What is this called?

humble siren
#

Is't possible for a discord bot to local side mute?
If not, is't possible for a discord bot to filter audio and only hear x user?

tawdry perch
#

wdym by hear x user?

humble siren
#

as in like a user with a certain role, or a certain discord ID

tawdry perch
#

you want to make a bot record others speaking..?

humble siren
#

i want to make a bot to only listen to user(s) with a certain @role

tawdry perch
#

;-; that sounds like a bad idea, recording others in discord voice chat

junior verge
royal lichen
#

Assuming you can find a module to receive audio from discord, each user is on their own audio stream, so you just ignore certain streams

humble siren
royal lichen
humble siren
#

we're making an Intercom system for voice chats

junior verge
tawdry perch
#

yes

junior verge
#

Or can it be a button as well

royal lichen
#

You can trigger it from a button too

junior verge
#

Ah great, where can I find that?

humble siren
#

@cobalt shoal

junior verge
#

!slash-commands

#

is there one?

maiden fable
tawdry perch
#

oh...

junior verge
humble siren
royal lichen
#

I think a library called nextcord is trying to do voice support, but I'm not sure it's done yet, other than that I don't know any others

humble siren
#

Alright, thank you a lot lemon_hyperpleased

wild imp
slate swan
#

Depends the library you're using.

#

It's mostly ephemeral=True keyword argument when using .reply().

slate swan
# pale palm Change `bot.get_user` to `client.get_user`.

Ignoring exception in command dm:
Traceback (most recent call last):
File "C:\Users\ADMIN\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\discord\ext\commands\core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "C:\Users\ADMIN\DeltaDiscordBot\main.py", line 135, in dm
user = bot.get_user(521325126722125874)
NameError: name 'bot' is not defined

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

Traceback (most recent call last):
File "C:\Users\ADMIN\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\discord\ext\commands\bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\ADMIN\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\discord\ext\commands\core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\ADMIN\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\discord\ext\commands\core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: NameError: name 'bot' is not defined

#

client.

royal jasper
#

how can i handle multiple reactions? example:

    def check(reaction, user):
        return user == ctx.author and str(reaction.emoji) in valid_reactions

    reaction, user = await fpr.wait_for('reaction_add', check=check)

    if str(reaction.emoji) == 'emoji one here'
      await ctx.send('you reacted emoji one')

    if str(reaction.emoji) == 'emoji one here'
      await ctx.send('you reacted emoji two')
slate swan
#

Not bot.

royal jasper
slate swan
#

And that's the purpose of wait_for

#

Wait until one, and only one, event is dispatched.

fair axle
#

is nextcord's UI better than dislashes?

junior verge
#
import discord
from discord.ext import commands 
from discord.ext.commands import MissingPermissions, has_permissions, CheckFailure 
import datetime


class Setup(commands.Cog):

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


    @cog_ext.cog_slash(name="test")
    async def _test(self, ctx: SlashContext):
        embed = discord.Embed(title="embed test")
        await ctx.send(content="test", embeds=[embed])
  

def setup(client):
    client.add_cog(Setup(client))
``` This doesn't work why?
loud junco
#
@commands.cooldown(1, 1, commands.BucketType.user)
async def inv(ctx: commands.Context):
  userid = str(ctx.author.id)
  res = '**__items__**\n'
  for item in items['mobdrop']:
    for i in bot.guilds:
      emoji = discord.utils.get(i.emojis, name = item)
      value = db[userid + item]
      if value > 0:
        res += f"{emoji}{item}: {value}\n"
```what is wrong here
royal lichen
#

Pycord already uses the discord namespace, although I'd recommend using a different fork.

outer basalt
#

I am having a issue where i am trying to send multiple embeds in a message via webhooks but its not working properly, i tried to print the embed titles its printing it correctly (['A member just edited their message.', 'Message deleted']) but not sending both embeds and sending only one embed.

code: https://mystb.in/DocumentaryNicknamePace.python

slate swan
#

No need to change anything.

royal lichen
#

It has a lot of bad design decisions that make it worse than other forks

#

Yes

patent surge
#

The bot is processing my commands twice

#

what happened

royal lichen
#

As an example it breaks support for proper linting by forcing users to incorrectly type hint slash commands

#

They have no plans to change it

loud junco
#
@commands.cooldown(1, 1, commands.BucketType.user)
async def inv(ctx: commands.Context):
  userid = str(ctx.author.id)
  res = '**__items__**\n'
  for item in items['mobdrop']:
    for i in bot.guilds:
      emoji = discord.utils.get(i.emojis, name = item)
      value = db[userid + item]
      if value > 0:
        res += f"{emoji}{item}: {value}\n"
```whats wrong
#

someone help?

#

;-;

#

rpm help

junior verge
#
import discord
from discord.ext import commands
from discord_slash import cog_ext

class Cogs(commands.Cog):

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

    @cog_ext.cog_slash(name='Ping', description='Sends Pong')
    async def ping(self, ctx):
        await ctx.send('pong')


def setup(client):
    client.add_cog(Cogs(client))
``` What is wrong here
slate swan
#

You probably have bot

loud junco
#

where is ur client

junior verge
loud junco
#

client = client.commands()

#

something like this i forgot

junior verge
#

It's in cogs

loud junco
#

oo

junior verge
#

so that is in the main file

loud junco
#

but its not defined anyway

junior verge
#
client = commands.Bot(command_prefix='.')
``` is in main
loud junco
#

hmm

junior verge
#

Yeah it's when I was trying to work with slash commands

#

Any idea

loud junco
#

its the client problem

#

its not defined

junior verge
#

How

loud junco
#

idk

#

maybe define it again

#
@bot.command(name = 'inv')
@commands.cooldown(1, 1, commands.BucketType.user)
async def inv(ctx: commands.Context):
  userid = str(ctx.author.id)
  res = '**__items__**\n'
  for item in items['mobdrop']:
    emoji = bot.get(ctx.message.guild.emojis, name = item)
    value = db[userid + item]
    if value > 0:
      res += f"{emoji}{item}: {value}\n"
  res += '\n'
#

:/

maiden fable
#

!d discord.utils.get @loud junco

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/master/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.

Examples

Basic usage...
loud junco
#

bot.get => discord.utils.get

#

?

maiden fable
#

There's nothing like bot.get

loud junco
#

lol

#

stack overflow

loud junco
#

i dont wanna put id

#

there is tons of emoji

blissful crane
#
def register_commands(bot, *, ignore: list = [], stockfish_path=None):
    games = [game for game in ALL_GAMES if game not in ignore]
    class Games(*games):
        def __init__(self, bot):
            for cls in games:
                cls.__init__(self, bot)
    g = Games(bot)
    if stockfish_path:
        g.stockfish_path = stockfish_path
    bot.add_cog(Games(bot))

ALL_GAMES is a list of classes subclassed by commands.Cog

when i used this function, i provided a stockfish_path

but for some reason self.stockfish_path inside the class returns None instead of the path which i entered

why is it like that?

fair axle
#

anyone uses nextcord here?
if so please explain me a little about the UI
(i have read the docs don't send me the link)
@ me in response

patent surge
loud junco
#

=.= ur code is not working

patent surge
#

I use command once it runs twice

loud junco
#

:/

#

u use bot.group?

upbeat otter
#

regen your token

patent surge
#

no

upbeat otter
#

what

boreal ravine
#

how do i iterate through a guilds members and count them?

patent surge
#

For every command

#

I use once it runs twice

upbeat otter
royal lichen
loud junco
patent surge
slate swan
upbeat otter
slate swan
#

But to count just get the len

boreal ravine
loud junco
#

bot.guild

boreal ravine
#

not the bots servers

upbeat otter
slate swan
#

It's the same meaning though

upbeat otter
#

common name smh

maiden fable
#

Server goes brrr

slate swan
#

server => ui
guild => backend

maiden fable
#

Aw haha

loud junco
boreal ravine
maiden fable
#

Thanks for ignoring my messages @loud junco (:

loud junco
maiden fable
slate swan
#

You don't want to add the member object to your counter

boreal ravine
loud junco
boreal ravine
#

thanks

upbeat otter
#

!d discord.utils.get

unkempt canyonBOT
#

discord.utils.get(iterable, **attrs)```
A helper that returns the first element in the iterable that meets all the traits passed in `attrs`. This is an alternative for [`find()`](https://discordpy.readthedocs.io/en/master/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.

Examples

Basic usage...
upbeat otter
#

use this ^

loud junco
slate swan
#

And just use len()

maiden fable
#

I pointed to the same docs but okay

slate swan
#

Instead of iterating

loud junco
#

:/

upbeat otter
loud junco
maiden fable
#

Better is I'mma leave ¯_(ツ)_/¯

Got a lot more work to do

loud junco
#

;-;

boreal ravine
upbeat otter
loud junco
#

ok

#

thats what i did

upbeat otter
#

code

loud junco
#

ik

#

lemme show u

#
@bot.command(name = 'inv')
@commands.cooldown(1, 1, commands.BucketType.user)
async def inv(ctx: commands.Context):
  userid = str(ctx.author.id)
  res = '**__items__**\n'
  for item in items['mobdrop']:
    emoji = discord.utils.get(ctx.message.guild.emojis, name = item)
    value = db[userid + item]
    if value > 0:
      res += f"{emoji}{item}: {value}\n"
patent surge
#

Now it's working fine.
Thanks all of you

#

: )

boreal ravine
upbeat otter
#

yeah

loud junco
#

i changed it

upbeat otter
#

,-,

loud junco
#

so what do i chage to now

boreal ravine
#

show where you use get_emoji

upbeat otter
loud junco
#

hmmm

#

wait...

#

i dont have a get_emojifunc

#

🤣

graceful mulch
#

LOL

loud junco
#
def get_emoji():
  what do i write here
boreal ravine
#

show me the full error @loud junco and ofc you dont, your using the func

loud junco
lament mesa
#

send the full error

loud junco
lament mesa
#

client.get_emoji(emoji_id)

upbeat otter
#

^

lament mesa
#

pass in the id of the emoji

loud junco
#

i dont wanna put id in it

#

just the name

upbeat otter
#

wao

loud junco
#

cuz there is tons of them

#

like 30

lament mesa
#

then you could use discord.utils.get

#

discord.utils.get(client.emojis, name="name of the emoji")

upbeat otter
lament mesa
#

client

upbeat otter
#

explen

loud junco
#

im using bot = bot.commands()

#

so bot.emojis?

upbeat otter
loud junco
#

huh

#

they say
client =client.commands()
is noob

fair axle
#

is nextcord safe?

lament mesa
#

wdym safe?

loud junco
fair axle
#

cool

loud junco
#
@bot.command(name = 'inv')
@commands.cooldown(1, 1, commands.BucketType.user)
async def inv(ctx: commands.Context):
  userid = str(ctx.author.id)
  res = '**__items__**\n'
  for item in items['mobdrop']:
    emoji = discord.utils.get(bot.emojis, name = item)
    value = db[userid + item]
    if value > 0:
      res += f"{emoji}{item}: {value}\n"
loud junco
upbeat otter
#

,-,

loud junco
#

oo

#

i get it

#

im dumb

boreal ravine
#

bruh

upbeat otter
boreal ravine
#

u havent sent ur full error yet

loud junco
#

:D

#

its working

boreal ravine
#

gj

loud junco
#

😉

maiden fable
#

A word of advice, don't use replit since most of the times bots get ratelimited pretty fast

boreal ravine
#

imagine

maiden fable
#

¯_(ツ)_/¯

boreal ravine
#

my bot restarts like 30~ times a day if im making something surprised it hasnt been rate limited yet

upbeat otter
boreal ravine
loud junco
upbeat otter
#

everyday

maiden fable
loud junco
#

i restart it like all day long

loud junco
upbeat otter
boreal ravine
upbeat otter
#

lol

maiden fable
#

I never used replit for HunAI since, well, it's gonna get ratelimited as soon as it sends a single message lmao

maiden fable
#

What do u think

boreal ravine
#

an ai

maiden fable
#

A useless bot

boreal ravine
#

chatbot made by hunter

upbeat otter
#

ooo

upbeat otter
maiden fable
#

is it just me or literally everyone knows about it here

maiden fable
boreal ravine
#

you talk about it in disnake server

upbeat otter
maiden fable
#

Hunter --> Hun
AI --> AI

boreal ravine
#

i have eyes

maiden fable
maiden fable
upbeat otter
maiden fable
#

¯_(ツ)_/¯

boreal ravine
#

hm

#

chat died

maiden fable
#

Time for some economics then

visual island
#

@maiden fable still haven't been verified yet?

maiden fable
visual island
#

so long 😭

boreal ravine
#

sad

maiden fable
#

People in DDevs server say to wait and nothing else ¯_(ツ)_/¯

maiden fable
#

Let's just hope this waiting becomes worth it, else..... time to KMS :D

upbeat otter
maiden fable
#

and then @visual island says that I think negative

upbeat otter
upbeat otter
maiden fable
maiden fable
astral cobalt
#

Im trying to assign roles to users in my discord but for some reason I get this error 'NoneType' object has no attribute 'id' this is my code snippet for this client command python @client.command() async def element(ctx, member : discord.Member, role : discord.Role): #try_this = ctx.message.author try: role = get(member.guild.roles, id=role) await member.add_roles(role) except Exception as e: await ctx.send('There was an error running this command ' + str(e)) #if error else: await ctx.send("""Verified: {}""".format(user)) # no errors, say verified

kindred drum
#
yo anyone know a solution to this 
channel = bot.get_channel(GuildChannel.channel_id)
                        msg = await channel.fetch_message(reaction.message_id)
                        await msg.remove_reaction("💸", reaction.member)
                       
                    else:
                        Json_Items[i][x]['paypal_bool'] = True
                        Json_Items[i][x]['aids_variable'] = int((Json_Items[i][x]['aids_variable']) + 1)
                        json.dump(Json_Items, open("./all_user_rep.json", "w"), indent=1)
``````AttributeError: type object 'GuildChannel' has no attribute 'channel_id'```
maiden fable
#

BTW

#

when u do role: discord.Role, discord.py automatically converts the string to a discord.Role object

kindred drum
maiden fable
#

So u can simply do member.add_roles(role)

boreal ravine
#

it would

maiden fable
kindred drum
#

ah

kindred drum
#

🧠

maiden fable
#

Just experience ngl

boreal ravine
maiden fable
kindred drum
boreal ravine
#

no need to fetch/get it

astral cobalt
#
Traceback (most recent call last):
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 85, in wrapped
    ret = await coro(*args, **kwargs)
  File "main.py", line 30, in element
    await member.add_roles(role)
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/member.py", line 777, in add_roles
    await req(guild_id, user_id, role.id, reason=reason)
AttributeError: 'NoneType' object has no attribute 'id'

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

Traceback (most recent call last):
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 939, in invoke
    await ctx.command.invoke(ctx)
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 863, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 94, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'NoneType' object has no attribute 'id'```
maiden fable
cedar fern
#

anyone help me out pless

#

i need serious help

maiden fable
#

With?

cedar fern
#

anyone know how to create envirment variable

#

on repel it

boreal ravine
cedar fern
astral cobalt
#

@cedar fern Left side of screen its called secret tab

maiden fable
#

everyone is a replit expert except me

astral cobalt
#

First one is what its going to be named and second one is what the actual variable will contain

cedar fern
boreal ravine
#

anything

astral cobalt
#

What every you want to have

cedar fern
#

and value

astral cobalt
#

for me I have my discord bot key for my Auth

boreal ravine
#

you never said you wanted it to be anything specific

astral cobalt
#
value: "hello there"
print(test)
hello there```
boreal ravine
#

my eyes

astral cobalt
#

Srry

boreal ravine
#

why are you using light mode

astral cobalt
#

I like it

cedar fern
boreal ravine
astral cobalt
#

What ever the key is is the name of the variable

cedar fern
astral cobalt
#

@maiden fable So dont turn role into an object?

maiden fable
#

Just do member.add_roles(role)

astral cobalt
#

@cedar fern Im not sure I just joined this server

#

What should role be?

#

role = get(member.guild.roles, id=role)

maiden fable
#

The parameter in your function

upbeat otter
astral cobalt
#

still get the same error

#
@client.command()
async def element(ctx, member : discord.Member, role : discord.Role):
  await member.add_roles(role)```
upbeat otter
#

@maiden fable your chatbot remains functional while its gone for verification or not?

slate swan
slate swan
#

Since we can set custom banner and about me per server now

slate swan
#

Yes

upbeat otter
#

mhm

slate swan
cedar fern