#discord-bots

1 messages · Page 984 of 1

polar plinth
#

in the prefix folder?

#

not folder

#

file

#

the problem is here ig?

paper sluice
#

no can u send the traceback i.e error message

#

!traceback

unkempt canyonBOT
#

Please provide the full traceback for your exception in order to help us identify your issue.
While the last line of the error message tells us what kind of error you got,
the full traceback will tell us which line, and other critical information to solve your problem.
Please avoid screenshots so we can copy and paste parts of the message.

A full traceback could look like:

Traceback (most recent call last):
  File "my_file.py", line 5, in <module>
    add_three("6")
  File "my_file.py", line 2, in add_three
    a = num + 3
TypeError: can only concatenate str (not "int") to str

If the traceback is long, use our pastebin.

polar plinth
#
SyntaxError: invalid syntax

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

Traceback (most recent call last):
  File "main.py", line 23, in <module>
    client.load_extension(f"commands.{filename[:-3]}")
  File "/home/runner/Trent/venv/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 678, in load_extension
    self._load_from_module_spec(spec, name)
  File "/home/runner/Trent/venv/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 609, in _load_from_module_spec
    raise errors.ExtensionFailed(key, e) from e
discord.ext.commands.errors.ExtensionFailed: Extension 'commands.Prefix' raised an error: SyntaxError: invalid syntax (functions.py, line 68)
paper sluice
#

there is something wrong in ur Prefix.py

polar plinth
#

ig

#
Traceback (most recent call last):
  File "/home/runner/Trent/venv/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 606, in _load_from_module_spec
    spec.loader.exec_module(lib)
  File "<frozen importlib._bootstrap_external>", line 843, in exec_module
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
  File "/home/runner/Trent/commands/Prefix.py", line 6, in <module>
    import functions
  File "/home/runner/Trent/venv/lib/python3.8/site-packages/functions.py", line 68
    nodes = tuple(map(lambda (k, v): process_node(inner, k, v),
                             ^
SyntaxError: invalid syntax

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

Traceback (most recent call last):
  File "main.py", line 23, in <module>
    client.load_extension(f"commands.{filename[:-3]}")
  File "/home/runner/Trent/venv/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 678, in load_extension
    self._load_from_module_spec(spec, name)
  File "/home/runner/Trent/venv/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 609, in _load_from_module_spec
    raise errors.ExtensionFailed(key, e) from e
discord.ext.commands.errors.ExtensionFailed: Extension 'commands.Prefix' raised an error: SyntaxError: invalid syntax (functions.py, line 68)
#

the thing is i have no file called functions

#

or am i dumb?

#

@slate swan

paper sluice
quaint epoch
#

btw, can you do ```py
@bot.command()
async def foo(ctx):
pass

@foo.on_error()
async def on_error(error):
print('error')```

paper sluice
#

it should be lambda k,v: ... instead of lambda (k,v): ...

quaint epoch
#

ofc you can just set a lambda to a variable and pass the args on that

paper sluice
#

oh yea, didnt even see that lol

polar plinth
#

dude i dont even know where i typed it, functions.py isnt a file

#

from prefix?

#

oke wait

#

need to be in commands cuz of the help cmd

#

its same as cogs just other file

#

message to long wait

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.

polar plinth
#

wait

#

ya ok

paper sluice
#

nah thats just discord's shitty way to flagging links, if a link ends with .py it does that

polar plinth
#

not all needed

paper sluice
#

what is functions???

polar plinth
#

oh wait

#

ohhh

#

thing is

#

i need functions

slate swan
#

How do i use discord.Client.wait_for for multiple events? Specifically message and reaction_add

paper sluice
polar plinth
#

bru

torn sail
# slate swan How do i use ``discord.Client.wait_for`` for multiple events? Specifically ``mes...
done, pending = await asyncio.wait([
                    bot.loop.create_task(bot.wait_for('message')),
                    bot.loop.create_task(bot.wait_for('reaction_add'))
                ], return_when=asyncio.FIRST_COMPLETED)

try:
    stuff = done.pop().result()
except ...:
    # If the first finished task died for any reason,
    # the exception will be replayed here.
for future in done:
    # If any exception happened in any other done tasks
    # we don't care about the exception, but don't want the noise of
    # non-retrieved exceptions
    future.exception()

for future in pending:
    future.cancel()  # we don't need these anymore
slate swan
#

Oh damn

#

thanks

torn sail
#

Well they have to work together

paper sluice
#

what do u want to add buttons to?

#

u will obv have to make the 3 buttons and send it with the embed

onyx apex
#

Hello, I am trying to set up a random gif generator from Tenor using the API Key.

I can get it to generate the 1st gif in the query, but not a random one... Can anyone help? Here is my code and a photo (sowing every call of the command generates a new number but how I can get that to pick a new gif, I don't know 😢 )

@commands.command()
  @commands.has_guild_permissions(send_messages=True, embed_links=True)
  async def gif(self, ctx, query):  
      async with aiohttp.ClientSession() as session:
          TENOR_API_TOKEN = 'XXXXXXXXXXXXX'
          embed = discord.Embed(colour=discord.Colour.dark_red())
          response = await session.get(f'https://api.tenor.com/v1/search?q={query}&key={TENOR_API_TOKEN}&limit=30&media_filter=basic')
          data = json.loads(await response.text())
          gif_choice = random.randint(0, 29)
          for result in data['results']:
              for media in result['media']:
                  print(gif_choice)
                  embed.set_image(url=data['media'][gif_choice]['url'])
      await session.close()
      await ctx.send(embed=embed)
#

However, if I change embed.set_image(url=data['media'][gif_choice]['url']) to embed.set_image(url=media['gif']['url']) it shows the first gif from the query as shown in this photo... It doesn't randomise from the top 30 on that search 😢

loud junco
#

he is desperate for trying to help me

onyx apex
#

??

loud junco
#

go and take a look

loud junco
onyx apex
loud junco
loud junco
slate swan
slate swan
#

the code is over-complicated than it should be

slate swan
slate swan
onyx apex
slate swan
#

I think it should be something like py array = [r for r in data["results"]["media"] data = json.load(await response.text()) embed.set_image(url=random.choice(array))
note : idk though, i've never used the api so ye

slate swan
#

Btw do ["results"] and ["media"] return a list?

slate swan
slate swan
#

How can my bot check if someone else than the author reacted to the message and then send a message, that only the guy read? Like Dank Memer or is it not possible?

slate swan
unkempt canyonBOT
#

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

Waits for a WebSocket event to be dispatched.

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

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

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

This function returns the **first event that meets the requirements**...
slate swan
#

There is an event but i forgot the event name

#

I think its on_reaction_raw

onyx apex
slate swan
#

install the module

#

!dotevn

unkempt canyonBOT
#

Using .env files in Python

.env (dotenv) files are a type of file commonly used for storing application secrets and variables, for example API tokens and URLs, although they may also be used for storing other configurable values. While they are commonly used for storing secrets, at a high level their purpose is to load environment variables into a program.

Dotenv files are especially suited for storing secrets as they are a key-value store in a file, which can be easily loaded in most programming languages and ignored by version control systems like Git with a single entry in a .gitignore file.

In python you can use dotenv files with the python-dotenv module from PyPI, which can be installed with pip install python-dotenv. To use dotenv files you'll first need a file called .env, with content such as the following:

TOKEN=a00418c85bff087b49f23923efe40aa5

Next, in your main Python file, you need to load the environment variables from the dotenv file you just created:

from dotenv import load_dotenv()

load_dotenv(".env")

The variables from the file have now been loaded into your programs environment, and you can access them using os.getenv() anywhere in your program, like this:

from os import getenv

my_token = getenv("TOKEN")

For further reading about tokens and secrets, please read this explanation.

slate swan
#

wait u can get that with os module

#

iirc there is a library called dotenv

slate swan
onyx apex
slate swan
unkempt canyonBOT
#

Hey @onyx apex!

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

velvet compass
slate swan
#

Oh then

slate swan
slate swan
#

@onyx apex since that returns a list of urls then make a random.choice to get "random url" from the list

slate swan
#

random.choice(data["results"]["url"]) something like this

#

I think its python-dotenv

slate swan
slate swan
slate swan
#

oh no

#

:<<

#

i just slept when i was making giveaway cmd

#

Maybe eh restart ur ide?

#

FortniteDude idrk

#

pip install python-dotenv

from dotenv import load_dotenv
import os

load_dotenv()

_s = os.environ.get("key")
velvet compass
#

Did you install dotenv or python-dotenv?

#

Oh

#

I'm too slow

slate swan
#

...?

#

you dont know the "name" of the library you installed?

onyx apex
slate swan
# slate swan nah

well, you need dpy 2 master branch installed to use its slash cmds which are horrible

#

!e py import random d = {"d" : {"url": "7", "url" : "3"}} print(random.choice(d["d"]["url"]))

#

Oh

unkempt canyonBOT
#

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

3
onyx apex
slate swan
#

Well im not sure 🤷🏾🤷🏾

#

this conversation is fun and painful to watch

#

😔

#

hi

onyx apex
slate swan
#

.

slate swan
#

await channel.send("uwu")

#

do it after all your imports

#
from dotenv import load_dotenv
import os
import discord
import config
load_dotenv()
token = os.environ.get("BOT_TOKEN")

bot.run(token)
slate swan
#
if any((channel for channel in ctx.guild.text_channels if channel.mention == msg.content)):
#

oh you're using this huh

#

..

#

well, you cant really send messages anyways like that

#

then ill use this only

#

bad

#

huh

#

wow which theme

#

maybe fit that into a list comprehension?

[await channel.send("exists") for channel in ctx.guild.text_channels if channel.mention == msg.content else await channel.send("doesnt exist")]
#

hm, the dotenv module still doesnt work, weird

slate swan
#

run: python -m pip install python-dotenv in the terminal, then restart your ide

slate swan
#

then you gotta use a for loop

#

which is bad (according to where you're using it)

#

..

#

then instead of waitfor i need to use like this !g st #bot-commands 1 giveaway title

#

;-;

#

sheesh, do you have multiple versions of python installed?

#

why cant i import Button and ButtonStyle?

#

ew, what library is that

#

well, then you know what to do

#

seemed like a 3rd party lib

#

they're the same?

#

idk, maybe?

#

uh

#

<@&831776746206265384> (sorry for the ping, somebody posted an inappropriate video which they deleted)

#

noice

#

attacking

#

idk some kind of missile target

#

at begn

#

probably a terrorism supporting one

#

ye

#

pip install ig

#

change your python version in vs code from the bottom left corner. Period.

#

..

slate swan
#

they got multiple python versions installed

#

and I'm getting ignored for that

#

I think I will just go away from here now

#

Do. You. Have. Multiple. Python. Versions. Installed. ?.

#

..

#

wha-

#

then check huh 😭

#

is there any input method in discord ui

slate swan
#

modals ok

loud junco
#

if x.type == string:

slate swan
# slate swan modals ok
from discord import ui

class Questionnaire(ui.Modal, title='Questionnaire Response'):
    name = ui.TextInput(label='Name')
    answer = ui.TextInput(label='Answer', style=discord.TextStyle.paragraph)

    async def on_submit(self, interaction: discord.Interaction):
        await interaction.response.send_message(f'Thanks for your response, {self.name}!', ephemeral=True)
loud junco
slate swan
loud junco
#

ok

slate swan
#

its best ever for what im doing!!!

slate swan
loud junco
#

congrats

slate swan
#

aval in disnake?

loud junco
#

🥳

slate swan
#

why do I always get ignored 😔

loud junco
slate swan
loud junco
#

alt f4
jkjk

slate swan
#

||I told them to restart twice before so idk if that really is the issue||

slate swan
loud junco
slate swan
loud junco
#

im going to sleep byebyeeee

slate swan
loud junco
loud junco
slate swan
loud junco
#

its 1030pm here so im sleeping

loud junco
slate swan
#

:)

slate swan
loud junco
#

oo

#

byebye

slate swan
#

bye

#

@slate swan how long are you online?

#

@slate swan uh why?

#

Cuz they be been here since morning

#

..

#

Lol

unkempt canyonBOT
#
Resources

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

slate swan
#

..

slate swan
#

lol

#

It might help? down_syndromesmile

#

i think he will show u how to "run file" "download modules" etc (not sure) if u still need help just go to that guy's channel

slate swan
#

pfftt

#

sure

#

go ahead

maiden fable
#

Wait

#

What's that syntax highlighting?

#

Nvm it's JS

#

msg = await ctx.send()
await msg.edit(embed=None, content="Embeds Removed!")

#

Bro

#

Don't do dpy if udk basic Python

slate swan
maiden fable
#

Cba to edit the code even when I gave the code he literally has to copy paste

edgy blade
maiden fable
#

Why do u have a try except?

#

you are not making and sending the embed tho, in the ctx.send

slate swan
#

how do i tell if an arg is a number, i tried

@commands.command()
async def _info(self, ctx, *, var):
    if not isinstance(var, int):
        return await ctx.reply('Not XUID')

    await ctx.reply('Is XUID')

and it doesnt work

#

it still gives an index out of range error

final iron
#

You need to type hint it to an int

slate swan
pliant gulch
#

!d str.isdigit

unkempt canyonBOT
#

str.isdigit()```
Return `True` if all characters in the string are digits and there is at least one character, `False` otherwise. Digits include decimal characters and digits that need special handling, such as the compatibility superscript digits. This covers digits which cannot be used to form numbers in base 10, like the Kharosthi numbers. Formally, a digit is a character that has the property value Numeric\_Type=Digit or Numeric\_Type=Decimal.
final iron
#

I was about to do that

trim fulcrum
#

how can i make it where if you put a certain word in your status it sends a message and adds a role and if you remove that word it removes role and sends a message

stone moon
#

how can i find a numeric role in a users roles?

slate swan
#

I watched a youtube Tutorial on modals and thats literally the same as in the video

boreal ravine
lofty pecan
boreal ravine
slate swan
#

how do i hidden reply to a message

#

with ctx.reply

lofty pecan
lofty pecan
lofty pecan
#

(ctx.author).roles

trim fulcrum
#

how can i make it where if you put a certain word in your status it sends a message and adds a role and if you remove that word it removes role and sends a message

lofty pecan
lofty pecan
lofty pecan
slate swan
lofty pecan
#

I answered them already

slate swan
slate swan
stone moon
lofty pecan
cloud dawn
lofty pecan
opal cosmos
#

hey so what does the email scope do on my discord bot application?

lofty pecan
cloud dawn
#

!d str.isdigit

unkempt canyonBOT
#

str.isdigit()```
Return `True` if all characters in the string are digits and there is at least one character, `False` otherwise. Digits include decimal characters and digits that need special handling, such as the compatibility superscript digits. This covers digits which cannot be used to form numbers in base 10, like the Kharosthi numbers. Formally, a digit is a character that has the property value Numeric\_Type=Digit or Numeric\_Type=Decimal.
cloud dawn
compact ruin
#
if result[8] >= 50:
   print("Value is Greater Than 50")
else:
  print("Value is less than 50")
TypeError: 'NoneType' object is not subscriptable

The Object has a value of 51..For whatever reason it says its a None Type...

#

Does Anyone Know Why?

cloud dawn
#

well result variable is None

#

Print just result

compact ruin
cloud dawn
lofty pecan
#

sultan, the error means that the object you check in is None

compact ruin
lofty pecan
#

what does the print say

cloud dawn
compact ruin
#

I want it the check the 8th row

lofty pecan
#

what does it look like

#

is it a json?

compact ruin
#

SQL

cloud dawn
lofty pecan
#

how did you get the result

compact ruin
#
db = sqlite3.connect('data/Test.sqlite')
        cursor = db.cursor()
        cursor.execute(f"SELECT * FROM TestTable WHERE user = {user.id}")
        result = cursor.fetchone()
scarlet aurora
#
    @commands.command()
    @commands.has_permissions(manage_messages=True)
    async def tempmute(self, ctx, member:discord.Member, *, time:TimeConverter = None, reason="Reason unspecified"):
        role = discord.utils.get(ctx.guild.roles, name="Muted")
        await member.add_roles(role)
        await ctx.message.delete()
        embed = discord.Embed(
            title=f"Tempmute: {member}", description=f"Reason: {reason}\nDuration: {time}\nBy: {ctx.author.mention}")
        await ctx.send(embed=embed)
        if time:
            await asyncio.sleep(time)
            await member.remove_roles(role)``` Can someone tell me why my tempmute is broken? It doesn't unmute after specified time
lofty pecan
cloud dawn
#

!tags

scarlet aurora
lofty pecan
#

cursor.execute("SELECT * FROM TestTable WHERE user = ?", (user.id,))

cloud dawn
#

!sql-fstring

unkempt canyonBOT
#

SQL & f-strings
Don't use f-strings (f"") or other forms of "string interpolation" (%, +, .format) to inject data into a SQL query. It is an endless source of bugs and syntax errors. Additionally, in user-facing applications, it presents a major security risk via SQL injection.

Your database library should support "query parameters". A query parameter is a placeholder that you put in the SQL query. When the query is executed, you provide data to the database library, and the library inserts the data into the query for you, safely.

For example, the sqlite3 package supports using ? as a placeholder:

query = "SELECT * FROM stocks WHERE symbol = ?;"
params = ("RHAT",)
db.execute(query, params)

Note: Different database libraries support different placeholder styles, e.g. %s and $1. Consult your library's documentation for details.

See Also
Extended Example with SQLite (search for "Instead, use the DB-API's parameter substitution")
PEP-249 - A specification of how database libraries in Python should work

compact ruin
lofty pecan
#

have a look here

lofty pecan
slate swan
#

@slate swan I've installed Discord.PY2 but all my code is wrong now because its still in version 1.7.3. How could i rewrite it the fastest way?

compact ruin
#

i see

cloud dawn
scarlet aurora
#

that's what I did for the test

scarlet aurora
#

10 second

#

and i waited like a min then just gave up

cloud dawn
slate swan
cloud dawn
lofty pecan
compact ruin
cloud dawn
lofty pecan
cloud dawn
lofty pecan
#

anyway, if the result 51 there is nothing to iterate through

cloud dawn
#

He want's to index a row.

lofty pecan
#

@compact ruin in your data base, did you use int or str for the user id ?

cloud dawn
lofty pecan
#

yeah

#

That's why I asked about the type

compact ruin
lofty pecan
#

then why do you want to get the index

lofty pecan
#

omg are you trying to get the 9th row of your database

#

by typing [8]?

cloud dawn
lofty pecan
#

I didn't get that haha

compact ruin
cloud dawn
lofty pecan
#

yeah Sultan, you're selecting all the rows with * and then just one with fetch_one

compact ruin
#

im trying to get the 8th row

lofty pecan
#

use fetch_all instead

#

if you want all the rows

cloud dawn
cloud dawn
lofty pecan
#

"SELECT *

lofty pecan
#

pretty much like a dictionnary

compact ruin
lofty pecan
#

result = cursor.fetchall()

compact ruin
#

Does not work

lofty pecan
#

there is no _

#

can you show the entire thing

cloud dawn
lofty pecan
#

yeah I told them about that already

compact ruin
#

hold up..

compact ruin
#

would a Cog listener be a problem?

cloud dawn
compact ruin
#

Cause for commands its working fine

lofty pecan
#

are you in a cog and is this a command

#

that's why I asked you to show the entire code

compact ruin
#

this is a listener.
Commands work fine

lofty pecan
worldly garnet
#

hello guys

#

i need some help

#

so you know how you can do like .get picture (picture used as an example, the bot would reply to this message by sending a photo)

#

idrk if we can pull it off in python cuz i learned it from js^

compact ruin
#
@commands.Cog.listener()
    async def on_message(self,message):
        db = sqlite3.connect('data/Test.sqlite')
        cursor = db.cursor()
        cursor.execute("SELECT * FROM TestTable WHERE member_id = ?", (user.id,))
        result = cursor.fetchone()
        await asyncio.sleep(0.5)
        if result[8] >= 50:
          print ("Value is Greater than 50)
        else:
          print ("Value is less than 50)
opal cosmos
#

ok so ive got a verify command im working on, where the bot will send a code and the user has to repeat it, but i wanna make it so the user only has a specific amount of time to repeat the code, how would i do this?

#
@bot.command()
async def verify(ctx):
  code = ("N6hT91")
  await ctx.send(f"**Please repeat the following phrase:**\n\n{code}")

  def check(m):
    return m.content == f"{code}" and m.channel == ctx.channel
  
  await bot.wait_for("message", check=check)
  await ctx.send("test successful")
lofty pecan
compact ruin
opal cosmos
lofty pecan
compact ruin
#

but yh one row

opal cosmos
opal cosmos
lofty pecan
compact ruin
lofty pecan
#

yeah

#

so as panda said earlier you don't want to SELECT *

#

just the column you desire

lofty pecan
#

to select the 8th column just put the column name instead of colmn

compact ruin
lofty pecan
#

!d discord.ext.commands.Bot.wait_for

unkempt canyonBOT
#

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

Waits for a WebSocket event to be dispatched.

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

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

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

This function returns the **first event that meets the requirements**...
lofty pecan
#

@opal cosmos

lofty pecan
compact ruin
lofty pecan
opal cosmos
compact ruin
#

Hold up lemme try something rq

lofty pecan
slate swan
lofty pecan
#

then the element you're looking for isn't in your databse

slate swan
paper sluice
#

hi

lofty pecan
#

sup'

compact ruin
#

Nvm fixed it, Works now.

lofty pecan
#

nice

compact ruin
#

One more question is there a way to get the reply to a message someone gives?

#

also ty for the help you lot

slate swan
#

Hello I’m making a bot that allows you to send message to a channel to echo your message via dms

But I wanna make it so if someone sends discord link it blocks them

maiden fable
#

istg APIs suck

lofty pecan
#

if message start with

lofty pecan
#

don't remember the syntax but something like that

maiden fable
slate swan
maiden fable
slate swan
slate swan
slate swan
slate swan
#

I love proxy servers and the fact that you can edit data using them

maiden fable
maiden fable
slate swan
#

You get the idea

#

He wanted help on how to reply

pliant gulch
unkempt canyonBOT
#

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

in
maiden fable
slate swan
#

@maiden fable uhhh help

maiden fable
#

?

opal cosmos
#
import discord
from discord.ext import commands
import random, os, asyncio
from discord.utils import get

bot = commands.Bot(command_prefix = "+")

@bot.command()
async def verify(ctx):
  code = ("N6hT91")
  await ctx.send(f"**Please repeat the following phrase:**\n\n{code}")

  def check(m):
    return m.content == f"{code}" and m.channel == ctx.channel

  member = ctx.author
  
  await bot.wait_for("message", timeout=10, check=check)
  role = get(member.server.roles, name="Test")
  await ctx.send("test successful")
  await ctx.author.add_roles(ctx.author, role)

bot.run(os.getenv("TOKEN"))

im still working on verify command and it wont give me the role. pls understand that i havent dealt with roles in a while so if its obvious i just dont realize it

#

it says member has no attribute server

slate swan
# maiden fable ?

how to establish just one connection to my sqlite db and store it in a bot variable 😔

opal cosmos
maiden fable
#

bot.db = sqlite3.connect()

slate swan
slate swan
maiden fable
#

just use a task and set the count to 1

opal cosmos
slate swan
maiden fable
#

Still u need an async function

#

Idk if u need to await the connect call

slate swan
#

you need to

slate swan
#

sift showed me an example a few days ago

#

i cant find it now 😔

maiden fable
#

then either use a task, event or the run (or was it start?) function

pliant gulch
#
class Client(discord.Client):

    async def setup_hook(self) -> None:
        self.db = await connect(...)
opal cosmos
slate swan
lofty pecan
paper sluice
#

u can do something like this

async with aiomysql.connect() as con:
    bot.var = con

if it can be used as a cm

opal cosmos
pliant gulch
#

So, in some cases using bot.var in this case, would be closed already

lofty pecan
pliant gulch
#

In this case you want to use it for the life-time of the bot, so you should open it without a context manager, then manually close inside of Bot.close

#

Which you can override to do so quite easily

opal cosmos
paper sluice
opal cosmos
paper sluice
#

what i mean is something like this

bot = ur bot
async with bot:
  async with aio...:
    bot.var = ...
    bot.start()
pliant gulch
#

Ah that makes more sense

#

But nesting the context managers just look weird IMO

#

But then again, not even sure if discord.py actually adds the signal callbacks correctly to handle SIGTERM (On windows that is)

opal cosmos
maiden fable
#

member.add_roles

#

Not bot.add_roles

#

Where member is a discord.Member object

opal cosmos
#

i have the name right tho

maiden fable
#

code

#

Hi

opal cosmos
slate swan
#

@slate swan How can I rewrite the slash commands? What to import? I tried googling it but couldn't find anything that helped me out

maiden fable
opal cosmos
maiden fable
#

No

opal cosmos
#

like as a package

maiden fable
#

Still no

opal cosmos
# maiden fable use dpy 2.0 or a fork
import discord
from discord.ext import commands
import random, os, asyncio
from discord.utils import get

bot = commands.Bot(command_prefix = "+")

@bot.command()
async def verify(ctx):
  code = ("N6hT91")
  await ctx.send(f"**Please repeat the following phrase:**\n\n{code}")

  def check(m):
    return m.content == f"{code}" and m.channel == ctx.channel

  member = ctx.author
  
  await bot.wait_for("message", timeout=10, check=check)
  
  role = get(member.guild.roles, id="965658220830007387")
  
  await ctx.send("test successful")
  await member.add_roles(member, role)

bot.run(os.getenv("TOKEN"))
#

i changed to id and it still didnt work

maiden fable
#

just do member.add_roles(discord.Object(role_id_here))

#

Also IDs are int and not string

opal cosmos
#

ooohhh

opal cosmos
slate swan
maiden fable
#

Cool

maiden fable
slate swan
opal cosmos
#

hmm

#

must be wrong package, lemme see if i can find the right one

opal cosmos
#

singular, discord-py-slash-command

#

gtg too so dm me if you have any more trouble

#

ill get back to you later

slate swan
opal cosmos
#

idk bro works for me

slate swan
#

ok

trim fulcrum
#

how can i make it where if you put a certain word in your status it sends a message and adds a role and if you remove that word it removes role and sends a message

unkempt canyonBOT
#

The activities that the user is currently doing.

Note

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

maiden fable
#

!d discord.CustomActivity

unkempt canyonBOT
#

class discord.CustomActivity(name, *, emoji=None, **extra)```
Represents a Custom activity from Discord.

x == y Checks if two activities are equal.

x != y Checks if two activities are not equal.

hash(x) Returns the activity’s hash.

str(x) Returns the custom status text.

New in version 1.3.
slate swan
onyx apex
#

Hello, I am trying to get my bot to auto-emoji react to the new member message, I have the following code, not working - where am I going wrong? 😦

@client.event
async def wavehello(ctx, messageid: int):
  channel = client.get_channel(-----------------)
  await ctx.fetch_message(messageid)
  message = await channel.fetch_message(channel.last_message_id)
  emoji = 'wave'
  await message.add_reaction(emoji)
brave forge
#

how to make the participant 's profile show the time in the voice ? Do you need a time module and a datetime package for this ?

weak gyro
#

I'm having errors starting my bot, I have no code exept the code to start it up

oblique laurel
#

Then wait for a bit while the msg is sent, or make your own custom welcome

weak gyro
#

how do i fix this?

winged bone
verbal silo
#

I'm getting this error when running index.py file "AttributeError: module 'discord' has no attribute 'app_commands' please help

weak gyro
#

i know NOTHING about python, im just following a guide

winged bone
#

You called .strip() on an object that was None

#

could you show your code?

oblique laurel
onyx apex
# oblique laurel Prob have that be in the on_member_join event ig

I have this currently:

@client.event
async def on_member_join(member):
    role = discord.utils.get(member.guild.roles, name='Skritt Recruit')
    await member.add_roles(role)
    channel = client.get_channel(---)
    await channel.send(f'{member.mention} just joined us! :slight_smile:')
    welcomemessage = f"Hello"
    embed = discord.Embed(title='Welcome!',
                          description=welcomemessage,
                          color=0xdb4b3c)
    button = manage_components.create_button(style=ButtonStyle.URL, label="Check out the events!",
                                               url=f'https://discord.com/channels/{--}/{--}')
    action_row = manage_components.create_actionrow(button)
    await member.send(embed=embed, components=[action_row])
    for channel in member.guild.channels:
        if channel.name.startswith('Total'):
            await channel.edit(name=f'Total Members: {member.guild.member_count}')

    message = await ((---).fetch_message(---).last_message_id)
    emoji = '\n{WAVING HAND SIGN}'
    await message.add_reaction(emoji)

Doesn't seem to add a reaction to the automatic message send by discord when someone joins

weak gyro
#

i just want a bot to use lol

winged bone
weak gyro
#

@winged boneAttributeError: 'NoneType' object has no attribute 'strip'?

#

dm me and ill show you my code

slate swan
weak gyro
#

i cant keep my pics from not being deleted

#

from os import getenv
from dotenv import load_dotenv

from discord import Client

client = Client()

@client.event
async def on_ready():
print(f'{client.user} has connected to Discord.')

load_dotenv()
client.run(getenv('TOKEN'))

#

there's my code

#

!code

unkempt canyonBOT
#

Here's how to format Python code on Discord:

```py
print('Hello world!')
```

These are backticks, not quotes. Check this out if you can't find the backtick key.

winged bone
#

He posted the error above

weak gyro
# slate swan your issue is?

Traceback (most recent call last):
File "C:\Users\User\Documents\CookieDiscordBoty\main.py", line 13, in <module>
client.run(getenv('TOKEN'))
File "C:\Users\User\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 631, in run
return future.result()
File "C:\Users\User\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 610, in runner
await self.start(*args, **kwargs)
File "C:\Users\User\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 573, in start
await self.login(*args)
File "C:\Users\User\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 424, in login
await self.http.static_login(token.strip())
AttributeError: 'NoneType' object has no attribute 'strip'

#

i can you show my ENV if you want

slate swan
weak gyro
#

DISCORD_TOKEN=eghouefuecfeuyveevheeh

#

thats all thats in my env

slate swan
#

then use the name of the key.....

#

getenv('DISCORD_TOKEN')

weak gyro
#

@slate swan

slate swan
#

@weak gyro

weak gyro
#

what

brave forge
#

how can I remove the underscore ?
from PIL import Image, ImageFont, ImageDraw

weak gyro
#

what

slate swan
#

underscore?

#

any difference? please elaborate

weak gyro
slate swan
#

why use an env in vsc? github pushes?

winged bone
#

@weak gyro
I also wanted to make a discord bot before I knew Python, you run into obstacles all the time. I recommend that you do an introduction to Python first. This is a free online "book": https://automatetheboringstuff.com/

slate swan
weak gyro
weak gyro
#

do i replace token with my token?

brave forge
#

how can I remove the underscore ?
from PIL import Image, ImageFont, ImageDraw
just the command where it is used works in in this line that I throw off all the words except from and import are underlined in yellow

paper sluice
west lily
#

Hello, I don't understand what the problem is. Can you help?

PS D:\discord.py> & C:/Users/user/AppData/Local/Programs/Python/Python310/python.exe d:/discord.py/main.py
Testing Bot Готов к работе!
Ignoring exception in command ban:
Traceback (most recent call last):
  File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\bot.py", line 939, in invoke
    await ctx.command.invoke(ctx)
  File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 855, in invoke
    await self.prepare(ctx)
  File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 789, in prepare
    await self._parse_arguments(ctx)
  File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 706, in _parse_arguments
    kwargs[name] = await self.transform(ctx, param)
  File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 552, in transform
    return await self.do_conversion(ctx, converter, argument, param)
  File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 505, in do_conversion
    return await self._actual_conversion(ctx, converter, argument, param)
  File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 451, in _actual_conversion
    ret = await instance.convert(ctx, argument)
  File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\converter.py", line 195, in convert
    raise MemberNotFound(argument)
discord.ext.commands.errors.MemberNotFound: Member "@gritty orchid я так решил" not found.
stone beacon
#

Why is pil not in the standard lib yet 🗿

#

Didn't they do away with the old one

tiny ibex
#

how to add custom emoji from url?

stone beacon
#

In the server

west lily
stone beacon
#

As in they're probably not in the server

stone beacon
winged bone
#

Read the error message

stone beacon
#

You supplied the right id/name etc to the function?

west lily
# stone beacon Hmm
from unicodedata import name
import discord
from discord.ext import commands
from pymongo import MongoClient
import os

class Ban(commands.Cog):

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

    @commands.command()
    @commands.has_permissions(administrator = True)
    async def ban(ctx, user, *, member: discord.Member,reason=None,):
        await member.ban(reason=reason)
        emb = discord.Embed(title='Забанен', color=0xff0000)
        emb.add_field(name='Модератор', value=ctx.author, inline=False)
        emb.add_field(name='Участник', value=member.mention, inline=False)
        emb.add_field(name='Причина', value=reason, inline=False)
        await member.send(f'Вы были забанены на сервере {name}. Модератор: {ctx.author}. Причина: {reason}.')
def setup(bot):
    bot.add_cog(Ban(bot))
#

full code

winged bone
#

hm seems like it didn't split the arguments correctly

#

could you remove the user parameter of the command and try again?

#

Seems like this is redundant

lofty pecan
#

Hi there, so my bot runs thanks to a script, but I was wondering if there was a way I could send message directly inside the console in channel the bot has access to

west lily
winged bone
lofty pecan
#

oke

winged bone
#

Could you try it?

rugged maple
#

I have a problem

#

from discord import

#

is not working for me

#

can someone please help me with it

weak gyro
#

@slate swanI ended up degrading to python 3.9, and it fixed it, now the bot is online

#

but, how do I make it say things now

slate swan
#

because of pipes?

dense swallow
#

can someone give me an example of a custom check in events?

grave summit
#

hi guys i have the redirect link to add my bot to the server but it isnt working

dense swallow
atomic robin
#
@client.command(pass_context=True)
async def ping(ctx, message: str, amount: int):
    pingscore = 0
    while pingscore != amount:
        await ctx.send(message)
        pingscore = pingscore + 1```

i learning how to make discord bots on python, i made command that will ping someone, how to make command that will immediately stop pinging without waiting for the end of the cycle?
cold sonnet
#

I'm gonna say one word, that's what your bot will be from the discord API

#

banned

#

temporarily

#

it's gonna be ratelimited

lime pelican
#

how do i do slash commands do a command thats setup as .work to be /work as a app command?

#

without fully recoding the command can i do a sub command

grave summit
#

im trying to add my bot to a friends server but its not adding for whatever reason

#

he has a react to verify for the server

#

could that cause issue of my bot not being able to join

#

oh yeah its getting stuck in the verify to react channel

cloud dawn
#

@verbal silo

slate swan
#

how can i use this in my command? i'm using ctx
this one is in my on_message

if not message.attachments:
slate swan
#

aight thanks

cloud dawn
#

!d discord.ext.commands.Context

unkempt canyonBOT
#
class discord.ext.commands.Context(*, message, bot, view, args=..., kwargs=..., prefix=None, command=None, invoked_with=None, invoked_parents=..., invoked_subcommand=None, ...)```
Represents the context in which a command is being invoked under.

This class contains a lot of meta data to help you understand more about the invocation context. This class is not created manually and is instead passed around to commands as the first parameter.

This class implements the [`Messageable`](https://discordpy.readthedocs.io/en/master/api.html#discord.abc.Messageable "discord.abc.Messageable") ABC.
idle laurel
#

when making a bot for multiple guilds is there anything different needed to allow commands to run without delays (waiting for commands to finish in other servers)

idle laurel
#

im assuming with the async functions its no needed?

#

but if any httpx requests i gotta user the async client

cloud dawn
cloud dawn
idle laurel
#

httpx have a built in async request?, or is aiohttp better?

cloud dawn
#

!pypi httpx

unkempt canyonBOT
idle laurel
#

im using httpx, not normal requests atm

cloud dawn
#

They are both pretty solid.

idle laurel
#

sound, was hoping i didnt need to change haha

pliant gulch
#

HTTPX Has both Sync and Async clients

vagrant tree
#

Quick question. I have a bot send a message in my server that should ping me. But instead, it just says has text. It's not pinging me like you would think it would. Does anyone know how I can actually make him ping me?

#

See. Wait

#

hold on

cloud dawn
#

!d discord.Member.mention

unkempt canyonBOT
cloud dawn
#

Or @vagrant tree

verbal silo
#

How do I fix "missing 1 required keyword-only argument: 'intents' error

cloud dawn
#

You need to pass intents

#

!d discord.Intents

unkempt canyonBOT
#

class discord.Intents(**kwargs)```
Wraps up a Discord gateway intent flag.

Similar to [`Permissions`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions "discord.Permissions"), the properties provided are two way. You can set and retrieve individual bits using the properties as if they were regular bools.

To construct an object you can pass keyword arguments denoting the flags to enable or disable.

This is used to disable certain gateway features that are unnecessary to run your bot. To make use of this, it is passed to the `intents` keyword argument of [`Client`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client "discord.Client").

New in version 1.5...
cloud dawn
#

!d discord.Client

unkempt canyonBOT
#

class discord.Client(*, intents, **options)```
Represents a client connection that connects to Discord. This class is used to interact with the Discord WebSocket and API.

A number of options can be passed to the [`Client`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client "discord.Client").
cloud dawn
#

As you can see it's a required arg

verbal silo
#

Yeah but what the final command looks like

unkempt canyonBOT
verbal silo
cloud dawn
#

client = discord.Client(intents=Intents())

verbal silo
lofty pecan
#

Hey there, is there a way using sqlite3 to get an image in the database and then fetch it to use it in an embed

cloud dawn
lofty pecan
#

should I just with wait_for get the message link ?

#

if the message get deleted it's bad tho

cloud dawn
lofty pecan
#

people are asked to give the image of the character they're making a card about

#

but if they just put the image it doesn't take the link

#

so i could use the message link I guess

verbal silo
cloud dawn
lofty pecan
slate swan
#

I'm still trying to Rewrite all my code to the D.PY 2.0 version but only the help command works can someone tell me why? There are no errors using the other commands

cloud dawn
lofty pecan
#

mmh

slate swan
slate swan
weak gyro
#

i've got my new bot online, how do i make commands and make it talk?

lofty pecan
#

Wdym by that

weak gyro
lofty pecan
#

Are you asking how to make discord commands?

weak gyro
#

yeah

lofty pecan
#

You should consider having a look at YouTube tutorials and the documentation of discord py then

#

That's what I did

weak gyro
#

mk

#

do i paste it after my like

#

bot.run("DISCORD_TOKEN")

brave forge
#

how to count how much time a participant spent in voice ?

weak gyro
#

when i do $ping it doesnt do anything

mortal dove
#

Is there any way to send a discord.Message object, instead of specifying content, attachments, embeds, etc?

weak gyro
#
from os import getenv
from dotenv import load_dotenv

from discord import Client

client = Client()

@client.event
async def on_ready():
    print(f'{client.user} has connected to Discord.')

load_dotenv()
client.run(getenv('DISCORD_TOKEN'))

import discord
from discord.ext import commands

bot = commands.Bot(command_prefix='$', intents=discord.Intents.all())

@bot.event
async def on_ready():
    print("bot is online")

@bot.command()
async def ping(ctx: commands.Context):
    await ctx.send("pong!")

bot.run("DISCORD_TOKEN")

jade jolt
#

bruh

unkempt canyonBOT
#
Resources

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

weak gyro
#

what did i do wrog in the code though

slate swan
#

Never had that kind of 'error'?

weak gyro
junior verge
#

I feel bad for him if we don't tell him

slate swan
#

i have this command and it's not sending anything and there's no error in console

@client.command()
@commands.cooldown(1, 120, commands.BucketType.user)
@commands.dm_only()
async def confess(ctx, *, coss):
        if str(ctx.author.id) in blacklist:
            await ctx.send("You have been blacklisted for a non-determained amount of time")
            return
        if not ctx.message.attachments:
            channel=client.get_channel(954816338755457104)
            confess=client.get_channel(931103626741563422)
            embed=discord.Embed(
                color=0x010914, description=f"`{coss}`")
            embed.set_footer(text="DM /confess <content>", icon_url={ctx.guild.icon_url})
            await ctx.send('Confession has been sent!')
            await channel.send(f"{ctx.author} - {ctx.author.id}\n{coss}`")
            await confess.send(embed=embed)
        if ctx.message.attachments:
                    channel=client.get_channel(954816338755457104)
                    confess=client.get_channel(931103626741563422)
                    embed2=discord.Embed(color=0x010914, description=f"{coss}")
                    embed.set_image(url=ctx.message.attachments[0].url)
                    await confess.send(embed=embed2)
                    await ctx.send('Confession has been sent!')
                    await channel.send(f"{ctx.author} - {ctx.author.id}\n{coss}\n{ctx.message.attachments[0].url}")

how can i fix it?

junior verge
#

@weak gyro Do you know Python? or did you just started discord.py without any knowledge of python

slate swan
#

aight wait

junior verge
#

Then see till where it gets

junior verge
#

Then learn python first

weak gyro
#

can you tell me how to fixx my code, first please

junior verge
#

Sure I guess

#

Send your code again what you got now

weak gyro
#

from os import getenv
from dotenv import load_dotenv

from discord import Client

client = Client()

@client.event
async def on_ready():
    print(f'{client.user} has connected to Discord.')

load_dotenv()
client.run(getenv('DISCORD_TOKEN'))

import discord
from discord.ext import commands

bot = commands.Bot(command_prefix='$', intents=discord.Intents.all())

@bot.event
async def on_ready():
    print("bot is online")

@bot.command()
async def ping(ctx: commands.Context):
    await ctx.send("pong!")

bot.run("DISCORD_TOKEN")

junior verge
#

!code

unkempt canyonBOT
#

Here's how to format Python code on Discord:

```py
print('Hello world!')
```

These are backticks, not quotes. Check this out if you can't find the backtick key.

weak gyro
#

im using backticks

junior verge
#

What

weak gyro
#
from os import getenv
from dotenv import load_dotenv

from discord import Client

client = Client()

@client.event
async def on_ready():
    print(f'{client.user} has connected to Discord.')

load_dotenv()
client.run(getenv('DISCORD_TOKEN'))

import discord
from discord.ext import commands

bot = commands.Bot(command_prefix='$', intents=discord.Intents.all())

@bot.event
async def on_ready():
    print("bot is online")

@bot.command()
async def ping(ctx: commands.Context):
    await ctx.send("pong!")

bot.run("DISCORD_TOKEN")

#

oh

junior verge
#

If you would know at least the basics of python

#

Then you can solve this easily

slate swan
# junior verge add prints

the argument work before i define the channel client.get_channel but after that it won't work anymore.

junior verge
#

Look at this example:

@client.event()
```py
And you got:
```py
@bot.event()
``` See any difference?
weak gyro
#

one's the client

#

and ones the bot

junior verge
junior verge
slate swan
#

my bad, it work after i define the channel.. it won't work after the embed i made.

weak gyro
junior verge
junior verge
slate swan
slate swan
#

aight thankss

junior verge
#

Doesn't give any errors for me either

#

Let me try some things alright

weak gyro
#

@junior vergegot it fixed

#
from os import getenv
from dotenv import load_dotenv
import discord
from discord.ext import commands

bot = commands.Bot(command_prefix='$', intents=discord.Intents.all())

@bot.event
async def on_ready():
    print(f'{bot.user} has connected to Discord.')

load_dotenv()
bot.run(getenv('DISCORD_TOKEN'))

@bot.event
async def on_ready():
    print("bot is online")

@bot.command()
async def ping(ctx: commands.Context):
    await ctx.send("pong!")

bot.run("DISCORD_TOKEN")

junior verge
#

Yeah it wasn't that hard.

#

Is this your exact code?

weak gyro
#

i was helped but im learning

junior verge
#

What are you even doing

#

This code still makes no sense bro

broken elk
#

I have a working discord bot online if anyone needs to look at it for help, as long as I can post links

#

Ah the link worked

#

Didn't know if it would be auto deleted

#

Should be a file button in the top left of the run box

vagrant tree
#

I'm using UptimeRobot and Replit to create a 24/7 Discord bot, but he keeps going down. I've watched a few tutorials, and I don't think I'm doing anything wrong. Will UptimeRobot sometimes just not work??

sick birch
#

It's meant for running quick tests and dispose of later

#

not for long-running processes like a discord bot

vagrant tree
sick birch
#

That doesn't mean it's good

vagrant tree
#

oooh

sick birch
#

Replit is very unreliable and is not a host

vagrant tree
#

man, that's disappointing

sick birch
#

Consider getting an actual host

vagrant tree
sick birch
#

Pick a provider first

#

We had a list of them

toxic thicket
#
@bot.command()
@commands.has_any_role(692760082085183519, 940008547993927691, 863878825376743475, 902292952381001779, 863879069253894166, 902292952381001779, 863879304110276668, 940008547993927691)
async def пред(ctx, member: discord.Member = None, *, reason = 'Отсутствует'):
    print(45)
    cursor.execute("""CREATE TABLE IF NOT EXISTS warning(guild_id BIGINT, user_id BIGINT, warn INT, count INT, moderator_id BIGINT, reasons VARCHAR)""")
    base.commit()
    print(1)
    
    warnings = cursor.execute("SELECT * FROM warning WHERE user_id = ? AND guild_id = ?", (member.id,ctx.guild.id)).fetchone()
    print("работает")
    
    
    if member is None:
        await ctx.send("Выберите участника")
        return
        
    if warnings is None:
        cursor.execute('INSERT INTO warning(guild_id, user_id, warn, count, moderator_id, reasons) VALUES(?, ?, ?, ?, ?, ?)', (ctx.guild.id,member.id,0,1,ctx.author.id,'Отсутствует'))
        base.commit()
        print(2222)
        cursor.execute(f'UPDATE warning SET warn = warn + 1 WHERE user_id = ? AND guild_id = ?', (member.id, ctx.guild.id))
        base.commit()
        await ctx.send(f"**{ctx.author.name}** Выдал предупреждение #{warnings[2]} {member} (случай # ) {reason}")
    else:
        cursor.execute(f'UPDATE warning SET warn = warn + 1 WHERE user_id = ? AND guild_id = ?', (member.id, ctx.guild.id))
        base.commit()
        await ctx.send(f"**{ctx.author.name}** Выдал предупреждение #{warnings[2]} {member} (случай # ) {reason}")     

how to make it so that if the reason is not specified, then Отсутствует is not written in the chat?

sick birch
#

They could but their infrastructure for the time being is not meant for that

#

Also the only people really doing that is new users to making discord bots

#

so it's really not all that much

vagrant tree
#

Wait, so if Replit is unreliable, then why does one of my bots always seem to be online?

sick birch
#

Yeah they have nodejs

sick birch
#

Sometime's it'll work and sometimes it won't

vagrant tree
#

mk

sick birch
#

One of reasons to not be using replit as a host

#

It's really just a use and throw quick test platform

toxic thicket
#

ok, but what about the error?

unkempt canyonBOT
#

Hey @mortal dove!

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

shell dune
#

best discord bot guides???

toxic thicket
shell dune
#

and resources?

mortal dove
#

@shell dune

#

I don't know how updated it is, but it's pretty recent.

shell dune
toxic thicket
#

Can you help me or can't you? @slate swan

mortal dove
sick birch
#

Im pretty sure that’s not the full error

sick birch
#

There we are

mortal dove
#

Hm?

sick birch
#

Looks like the issue is in the help command

#

But you already narrowed it down to that I see

#

You’re referring to “self.context “ but I’m not seeing where it’s being defined

mortal dove
#

It's defined in self because the main class inherits from commands.HelpCommand

#

it gives you a context attribute

polar ice
#

Hello is anyone available to offer any advice? I've got a loop, which works perfectly but only the first I run the code.
When the loop comes back round it doesn't seem to do as it should which is retrieve the data from the SQL DB

Can anyone shed any light to what im doing wrong?
https://paste.pythondiscord.com/butaritawo

I've posted the actual loop itself and also the first function. any help would be greatly appreciated.

Could it be because im using aysnc tasks?

scarlet aurora
#

does anyone here use heroku?

final pumice
#

wym

#

how does a rasberry pi work?

#

or how do i host the bot on it?

lofty pecan
lofty pecan
# final pumice wym

What is the requirements, the set up, how do you put the bot on the RP, and so on

#

Where did you find the instructions @final pumice lol

polar ice
#

Is it possible to have multiple different colors on one line?
All i can find is the syntax different colors?

polar ice
#

@slate swan am i being a mong but i cant seem to get it working 😄 ?

scarlet aurora
#

←[31m why does this appear when I run a .py file?

brave forge
#

@sick birch do you know where you can find info because in the command profile you can add the ability to see how many participants were in the voice for all the time on the server?

lone lichen
#

Hello! How do I use unix timestamps when sending a message.

tawny knoll
sullen plank
scarlet aurora
#

it literally just appears in the console as <-[31

boreal ravine
#

Show

brave forge
grave summit
#

im doing a discord bot with a command that interacts with api with a request.get to get statistics

#

but i need to format it through json.loads or json.dumps(i cant remember)

#

but im not sure how do this

boreal ravine
#

json.loads

grave summit
#

ok sweet

boreal ravine
#

no

grave summit
#

so far ive got that on one line

boreal ravine
#

json.loads = loads a string into a dict
json.dumps = dumps a dictionary

grave summit
#

ahhhh

#

so right now

#

{"symbol":"sea_shanties","floorPrice":8600000000,"listedCount":46,"avgPrice24hr":8850000000,"volumeAll":46204571198672}

#

this is the result of my command

#

so i want to json.loads the floorprice and just receieve that

#

and divide it by however many 0s

#

idk how to do multiple lines of code with discord bot command coding

#

and not sure if i can do all that on one line?

frozen patio
#

👀

grave summit
#
async def magic(ctx, *, me):
    await ctx.send(r.get(f'https://api-mainnet.magiceden.dev/v2/collections/{me}/stats').text), json.loads('floorPrice')
#

hi jonathan

frozen patio
#

Hi hazbob

grave summit
#

so right now ive got all that on one line of code

#

but i need to store the r.get request into object/variable?

#

cant remember what an object or variable is

#

im rambling through discord😂

mortal dove
#

Can anyone help? I'm making a help command, and get this error. Nor sure what I'm doing wrong, and I don't get any helpful things from traceback.
Code & error: https://paste.ofcode.org/bqYvxm7aRUbNyCeH9P2yDN
yes, that is the entire error
I also tried replacing the entire command body with just pass, and it still gives the same error.

boreal ravine
grave summit
#

ty ill give that a go

boreal ravine
#

👍

grave summit
#

is it apart of the @native granite

#

oh sorry

boreal ravine
#

yes

#

then index magiceden to get the floorPrice key

grave summit
#

how do i index sorry

#

also when i do the command above nothing is sent through to discord

boreal ravine
grave summit
#

!code

#
async def magic(ctx, *, me):
    magiceden = r.get(f"https://api-mainnet.magiceden.dev/v2/collections/{me}/stats')").json()
    dict = {'floorPrice': '10'}
    await ctx.send(magiceden)
#

when i run the magic command nothing is sending through to discord

#

im not sure if i have the wrong format of running multiple lines of code for discord.py

mortal dove
#

```py
(... your code here)
```

mortal dove
grave summit
#

im v new

#

but yes

mortal dove
#

dw, it's the line that goes like

bot = commands.Bot(
  #...
)
grave summit
#

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

#

its working for all my single line commands, like ctx.send(discord.File)

#

just this multiple line code im trying to do

#

isnt sendind

boreal ravine
boreal ravine
grave summit
#

oh im not sure about the message.intents

grave summit
#

not exactly sure what that means

boreal ravine
sly hamlet
#

what can i do about this? AttributeError: loop attribute cannot be accessed in non-async contexts. Consider using either an asynchronous main function and passing it to asyncio.run or using asynchronous initialisation hooks such as Client.setup_hook

torn sail
sly hamlet
#

can i in a cog?

torn sail
#

It needs to be an async function

#

You can override cog_load to start task

slate swan
#

i have a quart server and discord bot does anyone know how i can send a message in a channel when someone visits the quart page

sly hamlet
loud junco
#
if variable isnt in database:
  create one
else:
  pass
```how do u do this
sly hamlet
loud junco
#
if db[f'{userid}{itemname}] isnt in database:
  db[f'{userid}{itemname}] = 0
else:
  pass
torn sail
sly hamlet
#

It's not in a cog

#

I have it in my main file

torn sail
#

Then override the bots setup_hook

sly hamlet
#

I don't understand what that has to do with it though

torn sail
#

Because u can’t use the loop in a non async function

sly hamlet
#

Ooo

torn sail
#

And setup_hook is async and called at the start

sly hamlet
#

Nor do I know how to overwrite it 😑

torn sail
#

Subclass

sly hamlet
#

Yeah I think I'll just delete this for now

torn sail
#

Alrigt

sly hamlet
#

This seems like a problem that top.gg can help me with at a later date because it's their API

torn sail
sly hamlet
#

Yes but the loop relates back to their API

torn sail
#

not really

#

it relates to asyncio

sly hamlet
#

Yeah really it uses their API that's what the loop is for

torn sail
#

subclassing is simple if you wanna try it

from discord.ext import commands

class Bot(commands.Bot):
    async def setup_hook(self):
        self.loop.create_task(...)

bot = Bot(...)
sly hamlet
# torn sail subclassing is simple if you wanna try it ```py from discord.ext import commands...

so ```py
class Bot(commands.Bot):
async def setup_hook(self):
dbl_token = "Top.gg token" # set this to your bot's Top.gg token
bot.topggpy = topgg.DBLClient(bot, dbl_token)

    """This function runs every 30 minutes to automatically update your server count."""
    try:
        await bot.topggpy.post_guild_count()
        print(f"Posted server count ({bot.topggpy.guild_count})")
    except Exception as e:
        print(f"Failed to post server count\n{e.__class__.__name__}: {e}")

    self.loop.create_task(update_stats(self.bot))
sly hamlet
#

It seems to stop the bot from completely running though

torn sail
#

just remember to use this new Bot instead of commands.Bot

torn sail
#

do you need to post it right then or can u just post it in update_stats

#

@sly hamlet

sly hamlet
#

Needs to be posted probably in the run function

unkempt canyonBOT
#
not

6.11. Boolean operations


or_test  ::=  and_test | or_test "or" and_test
and_test ::=  not_test | and_test "and" not_test
not_test ::=  comparison | "not" not_test
``` In the context of Boolean operations, and also when expressions are used by control flow statements, the following values are interpreted as false: `False`, `None`, numeric zero of all types, and empty strings and containers (including strings, tuples, lists, dictionaries, sets and frozensets). All other values are interpreted as true. User-defined objects can customize their truth value by providing a `__bool__()` method.

The operator [`not`](https://docs.python.org/3/reference/expressions.html#not) yields `True` if its argument is false, `False` otherwise.
loud junco
torn sail
sly hamlet
#

Where are you getting that from I do not have a function called that

torn sail
#

in the self.loop.create_task

sly hamlet
#

It probably needs to be changed to setup hook

slate swan
#

why would you subclass the bot class over using the AbstractEventLoop

loud junco
#

hmm

#

its getting complicated

sly hamlet
#

It is plus that doesn't even work

slate swan
#

what

loud junco
#

is there a channel

#

where u can advertise thing?

#

like my discord bot

sly hamlet
slate swan
#

ah youre talking about that and what error

torn sail
#

There’s an wait_until_ready lockout

#

Probably from post_guild_count

#

So remove that part if update_stats posts

slate swan
boreal ravine
slate swan
boreal ravine
torn sail
#

It takes the bot

slate swan
#

*not

sly hamlet
boreal ravine
#

no.. remove .bot

torn sail
loud junco
#

i thought u cant

if f'{userid}{armor}' not in db:
```it just look weird but it works
boreal ravine
sly hamlet
boreal ravine
slate swan
sly hamlet
sly hamlet
#

Then self would not work and it would need to be bot

boreal ravine
#

it's like doing ```py
bot = Bot()
bot.bot

torn sail
sly hamlet
sly hamlet
torn sail
sly hamlet
#

My run function is a async

torn sail
#

Well then u can use loop there

sly hamlet
#

That's what I'm doing but inside of the setup hook we still get the same error and it still does not work

torn sail
#

Show code for run

sly hamlet
#
class Bot(commands.Bot):
    async def setup_hook(self):
        dbl_token = ""  # set this to your bot's Top.gg token
        bot.topggpy = topgg.DBLClient(bot, dbl_token)

        
        """This function runs every 30 minutes to automatically update your server count."""
        try:
            await self.topggpy.post_guild_count()
            print(f"Posted server count ({bot.topggpy.guild_count})")
        except Exception as e:
            print(f"Failed to post server count\n{e.__class__.__name__}: {e}")

        
async def sync_commands(bot):
    await bot.wait_until_ready()
    await bot.tree.sync()
    for guild in bot.guilds:
        await bot.tree.sync(guild=guild)

async def main():
    await bot.load_extension('cogs.botut')
    await bot.load_extension('cogs.fun')
    await bot.load_extension('cogs.nsfw')
    await bot.load_extension('cogs.pic')
    await bot.load_extension('cogs.helpmenu')
    await bot.load_extension('cogs.admin')
    await bot.load_extension('cogs.ut')
    await bot.load_extension('cogs.mute')
    await bot.load_extension('cogs.testmusic')
    asyncio.create_task(sync_commands(bot))
    bot.loop.create_task(setup_hook(bot))
    async with bot:
        await bot.start("")```
loud junco
#

i forgot how to make emoji into letters again

boreal ravine
loud junco
#

something like this
<:pogchop:917408218240671755>

slate swan
slate swan
#

nothing

#

it gets fired on startup

boreal ravine
#

and whats bot in the main function?

sly hamlet
slate swan
#

because bot its undefined

sly hamlet
#

So that's going to stop the entire bot from working and not even run with no error

slate swan
#

youre subclassing bot so your bot object is your own class so you would need to access an instance with self

slate swan
sly hamlet
#

It doesn't

#

The only thing that happens is that my cogs load nothing else happens the bot will not run

torn sail
#

Try removing the post guild count in the setup hook

sly hamlet
#

But it needs it in order to post it

torn sail
sly hamlet
torn sail
#

If that does already

sly hamlet
#

That is what it is doing it is posting it to top.gg

torn sail
#

No so you have a function called update_stats

#

What does it do

sly hamlet
#

No I do not

sly hamlet
brisk dune
#

Hey folks! Bit of a noob-esque question here: which library should I use? There's just so many forks out there! I've programmed a bot in discord.py before the discontinuation of it, so anything similar would be nice. I was thinking pycord, but will I make the right call with that?

torn sail
#

Oh well nvm

#

It was in the old code