#discord-bots

1 messages · Page 1055 of 1

brave forge
#

the words do so so keep to yourself

#

If I understood how to do it in words, I would not ask you, but just Google!

slate swan
#

you would make a subclass of the View class above the cog subclass so it would be define or just use an instance of it

brave forge
#

I want to learn how to do something like that!!!

slate swan
#

let me give you an example

modern fiber
#

Did I did this nicely?

@bot.command()
async def gban(ctx, user: disnake.User):
  for guild in bot.guilds:
    await guild.ban(user)```
#

Or I messed up smth?

brave forge
warped mirage
#

someone help me

brave forge
modern fiber
#

by one command. I guess thats the right way

slate swan
# brave forge I will be only glad and grateful
class Confirm(discord.ui.View):
    def __init__(self):
        super().__init__()
        self.value = None

    # When the confirm button is pressed, set the inner value to `True` and
    # stop the View from listening to more input.
    # We also send the user an ephemeral message that we're confirming their choice.
    @discord.ui.button(label='Confirm', style=discord.ButtonStyle.green)
    async def confirm(self, interaction: discord.Interaction, button: discord.ui.Button):
        await interaction.response.send_message('Confirming', ephemeral=True)
        self.value = True
        self.stop()

    # This one is similar to the confirmation button except sets the inner value to `False`
    @discord.ui.button(label='Cancel', style=discord.ButtonStyle.grey)
    async def cancel(self, interaction: discord.Interaction, button: discord.ui.Button):
        await interaction.response.send_message('Cancelling', ephemeral=True)
        self.value = False
        self.stop()

class MyCog(discord.ext.commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    # your command
    @commands.command()
    async def MyCommand(self, ctx):
        # creating an instance of your view
        MyView = Confirm()
        # sending a message with the instance of your View subclass
        await ctx.send("Message", view=MyView)

the most basic command i can give

slate swan
brave forge
slate swan
#

❤️

modern fiber
#

Can someone check this?

# GLOBAN BAN SYSTEM ------------------------------------------------------------------

@client.command(description="Globally bans user from all LARPC related servers.")
@command.has_permissions(administrator=True)
async def gban(ctx, user: disnake.User=None, *, reason=None):
 try:
    if (user == ctx.message.author or user == None):
        await ctx.send("You cannot globally ban yourself / that person!")
        return
    if (reason == None):
        await ctx.channel.send("You have to specify a reason!")

    for guild in client.guilds:
     guild.ban(user, reason=reason)
    print(user)
    print(guild)
    print(reason)

    await ctx.channel.send(f"{user} is **succesfully GLOBALLY banned** for {reason}!")
    channel = client.get_channel(801446246954827808)
    await channel.send(f"{user} has been **GLOBALLY banned** by {ctx.author} for **{reason}**!")
 except:
    await ctx.send(f"Error 404: I cannot GLOBAL ban {user}!")```
#

It's supposed to ban a person from all server he shares with bot.

slate swan
#

it can be done better in many ways

modern fiber
brave forge
#

@slate swan

    @discord.ui.button(style= discord.ButtonStyle.grey, emoji= "✅")
    async def button1_callback(self, button, interaction, ctx, * , member: discord.Member = None):
        await interaction.response.send_message(f'**{ctx.author.mention}** занялся сексом с **{member.mention}**')
        self.value = True
        self.stop()

    @discord.ui.button(style= discord.ButtonStyle.grey, emoji= "❌")
    async def button2_callback(self, button, interaction, member: discord.Member = None):
        await interaction.response.send_message(f'{member.mention}, вам отказал')
        self.value = False
        self.stop()```
I don't understand why he doesn't like this ctx!?
```Ignoring exception in view <MyView timeout=180.0 children=2> for item <Button style=<ButtonStyle.secondary: 2> url=None disabled=False label=None emoji=<PartialEmoji animated=False name='✅' id=None> row
=None>:
Traceback (most recent call last):
  File "C:\Users\ToxicPenguin\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ui\view.py", line 371, in _scheduled_task
    await item.callback(interaction)
TypeError: button1_callback() missing 1 required positional argument: 'ctx'
slate swan
# modern fiber Can someone check this? ```py # GLOBAN BAN SYSTEM ------------------------------...
  1. you should follow pep8
  2. no need for the () in the first if statement
  3. why the bare except, you should only have them in rare occasions
    4.you can just return a message object without returning anything to save a line
  4. again no need for the () in the second if statement and you should compare entities with is
  5. discord.Guild.ban is a coroutine
  6. you would easily get ratelimited
  7. Context already has a .send coroutine so no need to get a TextChannel instance
  8. i would check if the channel is in cache with Bot.get_channe()land if not i would use await Bot.fetch_channel()
dull terrace
#

async def button2_callback(self, button, interaction, ctx, member: discord.Member = None): @brave forge ?

#

oh it's in 1

slate swan
formal basin
#

What does this mean

warped mirage
#

guys

#

can someone help me fix my code please ...

brave forge
#

@dull terrace and it is better to blacklist them altogether so as not to see them

neat field
warped mirage
modern fiber
slate swan
# brave forge what ?

okay this is a simple button

@discord.ui.button(style= discord.ButtonStyle.grey, emoji= "✅")
async def button1_callback(self, button, interaction):
        await interaction.response.send_message("You pressed me!")

in all buttons it only takes the button argument which would be satisfied by a Button object and a interaction argument which would be satisfied by an Interaction object so Context would not be passed nor can it, so you would need to pass the context of the command which sends the view to your views subclass init

warped mirage
#

can someone help with my code

neat field
slate swan
# modern fiber that command uh

well im not gonna give you all together as i gave you all the problems and its better to do it yourself as you learn more!

neat field
#

that u can do, thats literally basic python

slate swan
#

basic python as said

formal basin
neat field
neat field
brave forge
slate swan
slate swan
slate swan
brave forge
slate swan
#

hes the owner of this server!

warped mirage
brave forge
warped mirage
#

if someone can help me out that would be great

brave forge
slate swan
#

😅

brave forge
#

They just couldn't fight back any other way

knotty agate
#

how can i tell if my bot is reciving DMs instead of server messages? i want to give my bot special commands that can only be activated through DMs, but the problem is my bot cant tell if its responding to an DM or not (which also causes attribute errors, but i know how to solve those)

@client.event
async def on_message(message):
  if message is a DM:
    # do special stuff
  else:
    # do normal stuff
slate swan
#

!d discord.Message.guild

unkempt canyonBOT
knotty agate
#

thx

warped mirage
slate swan
unkempt canyonBOT
formal basin
#

Did you import requests

slate swan
#

you would need to import the module and you should use aiohttp

#

so it wont block your bot

formal basin
#

import requests

slate swan
#

no no its not

#

!pypi aiohttp

unkempt canyonBOT
slate swan
#

youre confusing it with the async sqlite driver aiosqlite!

brave forge
slate swan
#

should remove request

#

!d aiohttp.request

unkempt canyonBOT
#
async-with aiohttp.request(method, url, *, params=None, data=None, json=None, headers=None, cookies=None, auth=None, allow_redirects=True, max_redirects=10, encoding='utf-8', ...)```
Asynchronous context manager for performing an asynchronous HTTP
request. Returns a [`ClientResponse`](https://aiohttp.readthedocs.io/en/stable/client_reference.html#aiohttp.ClientResponse "aiohttp.ClientResponse") response object.
slate swan
#

and you could use this!

smoky bloom
#

Hi can anybody tell me how is the guy who reacts to a message defined in code

warped mirage
slate swan
#

well you should be using the request function which the aiohttp module has

slate swan
smoky bloom
slate swan
smoky bloom
slate swan
unkempt canyonBOT
#

async for ... in users(*, limit=None, after=None)```
Returns an [asynchronous iterator](https://docs.python.org/3/glossary.html#term-asynchronous-iterator "(in Python v3.10)") representing the users that have reacted to the message.

The `after` parameter must represent a member
and meet the [`abc.Snowflake`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Snowflake "discord.abc.Snowflake") abc.

Changed in version 2.0: `limit` and `after` parameters are now keyword-only...
slate swan
#

maybe is that what youre looking for? i kinda need more context

warped mirage
#

!D indentation

unkempt canyonBOT
#

Leading whitespace (spaces and tabs) at the beginning of a logical line is used to compute the indentation level of the line, which in turn is used to determine the grouping of statements.

Tabs are replaced (from left to right) by one to eight spaces such that the total number of characters up to and including the replacement is a multiple of eight (this is intended to be the same rule as used by Unix). The total number of spaces preceding the first non-blank character then determines the line’s indentation. Indentation cannot be split over multiple physical lines using backslashes; the whitespace up to the first backslash determines the indentation.

smoky bloom
# slate swan maybe is that what youre looking for? i kinda need more context
@bot.event
async def on_member_join(member):
    if member.guild == bot.get_guild(960516503613079582):
      
      emoji = '✅'
      
      
      

      
      guild = bot.get_guild(960516503613079582)
      member = member
      Channel = bot.get_channel(960516503613079584)
      message = await bot.get_channel(960516503613079584).send(f"{member.mention} has joined the class")
      await message.add_reaction(emoji)
@bot.event
async def on_reaction_add(reaction, member):
    guild = bot.get_guild(960516503613079582)
    Channel = bot.get_channel(960516503613079584)
    if reaction.message.channel.id != Channel.id:
        return
    elif reaction.emoji == "✅":
      if member.id == 724460131110354984:
        
        Role = discord.utils.get(guild.roles,id=int(961235844704919562))
        await member.add_roles(Role)

This is my code

#

so umm if you could help with this it would be great

slate swan
# unkempt canyon

ah well yes you would check the users with this async iterator and since its a async iterator of user object you could just use the id attribute the User class has

unkempt canyonBOT
warped mirage
#

Can someone please help me...

slate swan
slate swan
#

!indents

unkempt canyonBOT
#

Indentation

Indentation is leading whitespace (spaces and tabs) at the beginning of a line of code. In the case of Python, they are used to determine the grouping of statements.

Spaces should be preferred over tabs. To be clear, this is in reference to the character itself, not the keys on a keyboard. Your editor/IDE should be configured to insert spaces when the TAB key is pressed. The amount of spaces should be a multiple of 4, except optionally in the case of continuation lines.

Example

def foo():
    bar = 'baz'  # indented one level
    if bar == 'baz':
        print('ham')  # indented two levels
    return bar  # indented one level

The first line is not indented. The next two lines are indented to be inside of the function definition. They will only run when the function is called. The fourth line is indented to be inside the if statement, and will only run if the if statement evaluates to True. The fifth and last line is like the 2nd and 3rd and will always run when the function is called. It effectively closes the if statement above as no more lines can be inside the if statement below that line.

Indentation is used after:
1. Compound statements (eg. if, while, for, try, with, def, class, and their counterparts)
2. Continuation lines

More Info
1. Indentation style guide
2. Tabs or Spaces?
3. Official docs on indentation

warped mirage
#

doesnt work i tried indenting and i still get the error

slate swan
#

may i see the error?

warped mirage
#

bruh ok sure

#

bunch of these

slate swan
#

show your code

warped mirage
#

can i send in a hastebin?

slate swan
#

!paste

unkempt canyonBOT
#

Pasting large amounts of code

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

After pasting your code, save it by clicking the 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.

warped mirage
#

oh wait

slate swan
#

😅

warped mirage
potent spear
slate swan
#

well your problem is with your context managers i assume as their indentations are quite off

warped mirage
potent spear
#

also, don't do shit in on_ready

slate swan
#

yeah you should make a task or overwrite setup_hook

warped mirage
warped mirage
potent spear
#

you've just copy pasted stuff without actually doing it correctly

#

let me guess, you came from sqlite and tried to make everything async via aiosqlite

warped mirage
#

yep 😦

#

well can u help me fix my thing or nah?

potent spear
#

this seems like an XY problem

slate swan
potent spear
#

the only time you actually need the cursor, is when you're fetching stuff, so you're actually SELECTING something
all the insert and UPDATE bullshit doesn't even need a cursor in aiosqlite

radiant shuttle
#
import discord
from datetime import datetime
TOKEN = "Token"
client = discord.Client()
@client.event
async def on_ready():
    print("RUNNING")
LOG_CHANNEL_ID = 977285171738976296


def generate_embed_description(message: discord.Message) -> str:
    # timestamp = datetime.now().strftime("%d/%m/%Y, %H:%M:%S %p")
    timestamp = message.created_at.strftime("%d/%m/%Y, %H:%M:%S %p")
    url = message.jump_url
    return (
        ":writing_hand: `Author:`\n"
        + message.author.mention
        + "\n\n :robot: `Channel:`\n"
        + message.channel.mention
        + "\n\n"
        + ":speech_balloon: `Message:` \n "
        + message.content.split("\n")[0]
        + "\n\n :watch:`Send at:`"
        + "\n **"
        + timestamp
        + "**"
        + f"\n [Jump to message]({url})"
    )


@client.event
async def on_message(message: discord.Message):
    if (
        message.channel.category.id != 977285171738976296
        or message.author.bot
        or message.content == "-clear"
    ):
        return

    embed = embed_for_user(message.author)
    if "\n" in message.content:
        embed.add_field(
            name=message.content.split("\n")[0],
            value="".join(message.content.split("\n")[1:]),
        )
    else:
        embed.description = generate_embed_description(message)
        embed.color = 0xDD4C59

    file = None
    if message.attachments:
        file = await message.attachments[0].to_file()
        file.filename = file.filename.replace("_", "")
        embed.set_image(url=f"attachment://{file.filename}")

    channel = client.get_channel(LOG_CHANNEL_ID)
    await channel.send(embed=embed, file=file)
    if message.channel.id == LOG_CHANNEL_ID:
        await message.delete()
def embed_for_user(user):
    embed = discord.Embed()
    embed.set_author(name=f"{client.user.name}", icon_url= client.user.avatar_url)
    return embed
client.run(TOKEN)
print(client.user.name)
#

where is the error its not running

warped mirage
potent spear
warped mirage
#

i did that and had so much errors

#

i can legit ss

potent spear
warped mirage
potent spear
warped mirage
#

so what should i remove from my code ?

potent spear
#

just ask line per line
"I had this single thing, how do I make that async?"

#

since all select queries etc should just be handled the same etc

smoky bloom
#
@bot.event
async def on_member_join(member):
    if member.guild == bot.get_guild(960516503613079582):
      
      emoji = '✅'
      
      
      

      
      guild = bot.get_guild(960516503613079582)
      member = member
      Channel = bot.get_channel(960516503613079584)
      message = await bot.get_channel(960516503613079584).send(f"{member.mention} has joined the class ! Bhak bsdk pehle May I come in ma'am bol")
      await message.add_reaction(emoji)
@bot.event
async def on_reaction_add(reaction, user: discord.User):
    guild = bot.get_guild(960516503613079582)
    Channel = bot.get_channel(960516503613079584)
    if reaction.message.channel.id != Channel.id:
        return
    elif reaction.emoji == "✅":
      
     
      Role = discord.utils.get(guild.roles,id=int(961235844704919562))
      await user.add_roles(Role)

Hi , just revised my code but still doesn't work . Can anybody help

potent spear
brave forge
#

how to import "ctx, * , member: discord.Member = None" via initiate in class.

smoky bloom
potent spear
smoky bloom
#

no errors on the console tho

warped mirage
#

is this fine? one by one

potent spear
potent spear
warped mirage
smoky bloom
potent spear
#

ever made a task?

warped mirage
#

no

potent spear
#

great

#

read some documentation about it, there are simple examples
so your task should just do what's in the on_ready
(this task will run as soon as the bot is online)

warped mirage
#

first lets look at the full code then focus on tasks

potent spear
#

do you just want me to fix it in 30 secs?

#

I'll just rewrite it all

warped mirage
potent spear
#

yeah, idk

warped mirage
#

ok sure

brave forge
warped mirage
#

it will mean alot

potent spear
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.

warped mirage
brave forge
slate swan
brave forge
potent spear
warped mirage
potent spear
slate swan
#

can we stop insulting each other?

warped mirage
slate swan
#

and people who follow rules arent called "rats" there called people with respect and sense so please stop.

warped mirage
#

entire code , i only didnt add token

slate swan
#

hey

#

hi hi!

#

shipit oki you got any ideas about the v2 perms, i mean can bots edit it anyways?

brave forge
warped mirage
#

@potent spear what i sent , is that fine?

slate swan
#

pls guys lets keep it civilize and lets respect eachother!

slate swan
potent spear
slate swan
#

i havent checked

#

mm lemme recheck the docs

potent spear
warped mirage
#

kk

warped mirage
slate swan
#

i havent seen any new endpoints in the Guild class

potent spear
warped mirage
#

wdym

potent spear
#

you removed the line

slate swan
potent spear
#

I have to wrap functions around that line

warped mirage
#

its client.run("token id")

slate swan
#

even in hikari, its just a pr rn

#

wasnt that released like 2 months ago or something like that how is it still a pr?

potent spear
#

I want the whole code again with that line included

warped mirage
#

ok lmao

slate swan
pliant gulch
pliant gulch
slate swan
#

the endpoints seems similar

slate swan
#

21 days actually*

#

😵‍💫

pliant gulch
#

It doesn’t make sense to not allow bots to edit their slash commands permissions as well. Considering the fact the bot account actually registers the command, etc

#

Otherwise that would be kind of a huge design flaw

slate swan
#

well yeah that makes sense
and from the pr i see they are allowing to edit the permissions so ig that works

#

the file exists in the ssame project file, im using cogs btw

#

inside the cogs folder?

#

no

#

it should be?

#

i've tried the code before without it being inside the cog folder and it worked fine

#

upto you, show your file structure

potent spear
slate swan
#

thats it

warped mirage
#

ok

slate swan
#

you run the main.py right? just making sure

#

yeah

#

try ../configs.json

potent spear
# slate swan thats it

I gotchu

from pathlib import Path

json_file_path = Path(__file__).parent.parent / "config.json"```
you should know what to do with this
warped mirage
#

@potent spear any updates?

slate swan
#
    pathe = Path(__file__).parent.parent / "config.json"
    config = json.load(open(pathe))
    prefix = config.get('Command Prefix')
```, code just stops and does nothing
potent spear
slate swan
#

thats just a copy paste mistake

#

yeah

potent spear
slate swan
#

😅

potent spear
#

WHERE you place those lines also matters

potent spear
warped mirage
#

@potent spear

#

under py if __name__ == '__main__': asyncio.run(main()) do i just do client.run(token) ?

potent spear
warped mirage
#

wdym

potent spear
warped mirage
#

Oh I see

#

Btw is that Save
New
Duplicate & Edit
Just
Text
Twitter

#

Is this important

potent spear
#

nope, that's a typo

warped mirage
#

Also did u change anything apart from the db shit or just that

potent spear
potent spear
hasty chasm
#

thanks i couldnt remember the name to save my life

warped mirage
#

Cuz I cba lmao

potent spear
warped mirage
#

Ok

potent spear
#

like

if member == None: 
  member = ctx.author```
changed to
```py
member = member or ctx.author```

also your hardcoded 
```py
# Do the command prefix which is > , ....

changed to

f"Do the command prefix which is {client.command_prefix} , ...```
potent spear
#

I already did that...

warped mirage
potent spear
#

because you were slightly annoying me with the same question for days

warped mirage
#

xD

#

btw can i have multiple tasks?

potent spear
#

just now look what I changed, so you can UNDERSTAND

warped mirage
#

ok]

potent spear
#

there's no task in your code...

cosmic sequoia
#

hi everyone! I want to make a dice game and I need the bot to send a message with consent and reaction, the person who was offered to play should click on the reaction and only after that the game will start. Please help me!

potent spear
potent spear
warped mirage
#

should i add another )

potent spear
#

yup

warped mirage
#

kk

#

lets see finally truth

warped mirage
# potent spear yup
File "C:\Users\Dom\Desktop\cluckz\main.py", line 215, in main
    client.loop.run_until_complete(setup_db())
  File "C:\Users\Dom\AppData\Local\Programs\Python\Python310\lib\asyncio\base_events.py", line 617, in run_until_complete
    self._check_running()
  File "C:\Users\Dom\AppData\Local\Programs\Python\Python310\lib\asyncio\base_events.py", line 579, in _check_running
    raise RuntimeError(
RuntimeError: Cannot run the event loop while another loop is running```
#

xd

potent spear
#

bad start

warped mirage
#

so what shall i do

cosmic sequoia
potent spear
potent spear
hasty chasm
#

@potent spear do i have to put these at the top of my cog for the task loop

        self.index = 0
        self.printer.start()
potent spear
hasty chasm
#

never used task loop its a new concept to me

potent spear
#

well, read what it is first

warped mirage
#
Traceback (most recent call last):
  File "C:\Users\Dom\Desktop\cluckz\main.py", line 220, in <module>
    asyncio.run(main())
  File "C:\Users\Dom\AppData\Local\Programs\Python\Python310\lib\asyncio\runners.py", line 44, in run
    return loop.run_until_complete(main)
  File "C:\Users\Dom\AppData\Local\Programs\Python\Python310\lib\asyncio\base_events.py", line 641, in run_until_complete
    return future.result()
  File "C:\Users\Dom\Desktop\cluckz\main.py", line 216, in main
    client.run("token")
  File "C:\Users\Dom\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 719, in run
    _cleanup_loop(loop)
  File "C:\Users\Dom\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 90, in _cleanup_loop
    _cancel_tasks(loop)
  File "C:\Users\Dom\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 75, in _cancel_tasks
    loop.run_until_complete(asyncio.gather(*tasks, return_exceptions=True))
  File "C:\Users\Dom\AppData\Local\Programs\Python\Python310\lib\asyncio\base_events.py", line 617, in run_until_complete
    self._check_running()
  File "C:\Users\Dom\AppData\Local\Programs\Python\Python310\lib\asyncio\base_events.py", line 579, in _check_running
    raise RuntimeError(
RuntimeError: Cannot run the event loop while another loop is running```
#

xd

#

@potent spear

potent spear
#

current code?

hasty chasm
#

@warped mirage how well do you know py

warped mirage
#

@potent spear

#

so i remove , tasks and @wild nestks.loop , just these 2 lines?

#

@wild nestks

potent spear
#

did I say otherwise?

warped mirage
potent spear
#

nope

warped mirage
#

well that then....

#

what shall i do

potent spear
#

exactly as said

warped mirage
#

, tasks , tasks .loop dont have to be there

potent spear
#

yup

warped mirage
# potent spear yup
Traceback (most recent call last):
  File "C:\Users\Dom\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 713, in run
    loop.run_forever()
  File "C:\Users\Dom\AppData\Local\Programs\Python\Python310\lib\asyncio\windows_events.py", line 321, in run_forever
    super().run_forever()
  File "C:\Users\Dom\AppData\Local\Programs\Python\Python310\lib\asyncio\base_events.py", line 585, in run_forever
    self._check_running()
  File "C:\Users\Dom\AppData\Local\Programs\Python\Python310\lib\asyncio\base_events.py", line 579, in _check_running
    raise RuntimeError(
RuntimeError: Cannot run the event loop while another loop is running

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\Dom\Desktop\cluckz\main.py", line 219, in <module>
    asyncio.run(main())
  File "C:\Users\Dom\AppData\Local\Programs\Python\Python310\lib\asyncio\runners.py", line 44, in run
    return loop.run_until_complete(main)
  File "C:\Users\Dom\AppData\Local\Programs\Python\Python310\lib\asyncio\base_events.py", line 641, in run_until_complete
    return future.result()
  File "C:\Users\Dom\Desktop\cluckz\main.py", line 215, in main
    client.run(token)
  File "C:\Users\Dom\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 719, in run
    _cleanup_loop(loop)
  File "C:\Users\Dom\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 90, in _cleanup_loop
    _cancel_tasks(loop)
  File "C:\Users\Dom\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 75, in _cancel_tasks
    loop.run_until_complete(asyncio.gather(*tasks, return
RuntimeError: Cannot run the event loop while another loop is running``` i cant show all but this is the most
hasty chasm
#

@warped mirage why dont you sort your code into cogs so its easier to use and more organized

hasty chasm
#

are you using just py in the code

warped mirage
#

yes

hasty chasm
#

how long ago did you start

warped mirage
#

i used to be good but i recently came back to coding , i know how to make a cog file but i need help adding the stuff into it , considering i need to fix my level system

hasty chasm
#

ill help you with cogs if you help me learn embeds

warped mirage
#

sure

#

embeds are easy

hasty chasm
#

check dms

warped mirage
#

@hasty chasm lets chat here its fine

hasty chasm
#

what are you hosing the code off of

#

github or something like vs

warped mirage
#

vs code

#

@potent spear um problem

slate swan
warped mirage
#

when i start bot , it auto goes back to py PS C:\Users\Dom\Desktop\cluckz>

potent spear
hasty chasm
#

@warped mirage any error?

warped mirage
#

nope

#

just auto new line and comes back

hasty chasm
#

is the bot online?

warped mirage
#

no

#

doesnt even start

hasty chasm
#

has it ever been online

warped mirage
#

yes bruh

hasty chasm
#

have you always used vs code

warped mirage
#

.....

#

@potent spear can u help me fix?

hasty chasm
#

because you need an enviroment file to get it online

potent spear
warped mirage
#

it just does this.......

slate swan
hasty chasm
#

your code doesnt have the word token anywhere is it in another file?

warped mirage
potent spear
hasty chasm
#

you cant host the bot because theres no token or env file so idk how you ever got it to go online

warped mirage
hasty chasm
#

make an environment file

warped mirage
#

bro

#

i use Client.run("Bot token id")

slate swan
potent spear
hasty chasm
#

you need an env file its required for vs

#

like the code wont listen unless you make an evn file and throw the token in there

warped mirage
#

I never used env bruh

#

I always use client.run

hasty chasm
#

you know what your right im sorry

potent spear
warped mirage
potent spear
#

and..?

warped mirage
#

Bro I copied what u sent me

heady sluice
#

I noticed you have a task without a cooldown

#

can u add a cooldown to it and see what happens?

potent spear
heady sluice
#

oh it's not there anymore

#

in Sniper's code

warped mirage
#

Ye I tested without the levelling system the bot works

#

Somethings not right .

potent spear
#
class Buttons:
  def __init__(participants):
    self.participants = participants

particip = ...
buttons = Button(partip)```
potent spear
warped mirage
#

FINALLY

slate swan
potent spear
#

hmm, well you could google that error optionally

warped mirage
#

@potent spear

#

Finally now I think it just needs some fixes

potent spear
#

coolcool

slate swan
#

fix

potent spear
slate swan
potent spear
#

I'm out guys, peace

#

I’m sorry to tell you, but you still have the XY problem

brave forge
warped mirage
#

@potent spear the code that u gave me breaks all my commands , non respond

#

the level system blocking them or smth

potent spear
#

You have an on_message, right?

brave forge
#

how do I import a mention of participants into a class using initiate?

warped mirage
#

what's ur point? @potent spear

sick birch
potent spear
#

That’ll do

brave forge
# sick birch "import a mention" what?
class MyView(discord.ui.View):
    def __init__(self):
        super().__init__()
        self.value = None

    @discord.ui.button(style= discord.ButtonStyle.grey, emoji= "✅")
    async def button1_callback(self, button, interaction):
        await interaction.response.send_message(f'**{ctx.author.mention}** занялся сексом с **{member.mention}**', initiate = True)
        self.value = True
        self.stop()

    @discord.ui.button(style= discord.ButtonStyle.grey, emoji= "❌")
    async def button2_callback(self, button, interaction):
        await interaction.response.send_message(f'{member.mention}, вам отказал', initiate = True)
        self.value = False
        self.stop()```
To make this work ({ctx.author.mention},  {member.mention})
sick birch
#

I'm not quite understanding

brave forge
#

@sick birch class does not see these mentions

sick birch
#

No, it doesn't

#

You can get the member using interaction.user

warped mirage
#

I’ll just try again tommorrow

brave forge
#

@sick birch how to mention the author and the mentioned participant ?

potent spear
warped mirage
#

It can’t line up with other awaits in the event . Got it

brave forge
#

@sick birch
ERROR

  File "C:\Users\ToxicPenguin\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ui\view.py", line 371, in _scheduled_task
    await item.callback(interaction)
  File "c:\Users\ToxicPenguin\Desktop\disocrd bot python\cogs\fun.py", line 16, in button1_callback
    await interaction.response.send_message(f'**{interaction.user}** занялся сексом с **{interaction.user.mention}**', initiate = True) 
TypeError: send_message() got an unexpected keyword argument 'initiate'```
sick birch
#

Remove initiate=True

brave forge
woeful trellis
#

@sick birch i need some help

sick birch
#

What's the issue?

woeful trellis
#

so my pip is broken, I can't update it I tried a few cmds in terminal. and in command prompt none worked.

sick birch
woeful trellis
#

ok

warped mirage
#

xD so many problems

potent spear
#

Just do command per command, I’m out

wet crystal
#

What do you need async and await for?
like what do these commands do?

sick birch
#

Usually you use them for I/O tasks (databases, network requests, files, etc) as these all take some time (relative to how fast python is)

echo wasp
#

!d discord message.delete

unkempt canyonBOT
#

In order to work with the library and the Discord API in general, we must first create a Discord Bot account.

Creating a Bot account is a pretty straightforward process.

echo wasp
#

@sick birch can you give me the right docs for when a message is deleted in a channel how do you recover it and post the image else where?

wet crystal
echo wasp
#

of it

unkempt canyonBOT
#

discord.on_message_delete(message)```
Called when a message is deleted. If the message is not found in the
internal message cache, then this event will not be called.
Messages might not be in cache if the message is too old
or the client is participating in high traffic guilds.

If this occurs increase the [`max_messages`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client") parameter
or use the [`on_raw_message_delete()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_raw_message_delete "discord.on_raw_message_delete") event instead.

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

yes

sick birch
#

Async defines a coroutine, which is basically a function that says "hey, this is not a regular function because if you call it, you won't get a return right away. it'll take some time"

#

Async functions are coroutines, which are a way to represent something that happens in the future

#

I like the name Javascript gives them: promises

#

It's a promise that something will happen later, just not right now

wet crystal
#

ohhhhh,
now i get it!

#

Thanks!

sick birch
#

And you can await these async functions like so:

async def this_function_takes_a_long_time():
  # do something that takes a long time
await this_function_takes_a_long_time() # python will do something else here
sick birch
#

Exactly. That's a network request which means it can take a while

sick birch
#

Not to you

echo wasp
#

just the ping time

sick birch
#

To the computer? It takes a really long time

wet crystal
echo wasp
sick birch
#

30ms, for example, to a computer is a really long time because they can do a lot in those 30ms

#

So instead of sitting around and doing nothing while you send a request, you can just go and do something else

slate swan
#
@client.event
async def on_guild_join(guild):
    try:
        link = await random.choice(guild.text_channels).create_invite()
    except:
        link = "I don't have perms to create an invite"
    channel = await client.fetch_channel(the channel id)
    await channel.send(f"Server Name - {guild.name} ({guild.id})\nServer Member Count - {len(guild.members)}\nServer Owner - {guild.owner}\nServer Invite - {link}") 
#

It says invalid sytax

hasty chasm
#
    @tasks.loop(seconds=3)
    async def DN_cycle():
        TH = bot.get_channel(977319265822711888)
        day = 0
        await TH.send('it is day' + str(day))
        day += 1
            


    @DN_cycle.before_loop
    async def before_DN_CYCLE(self):
        message = await self.bot.get_channel(977319265822711888).fetch_message(977301094524923955)
        if message.content == 'True':
            return
        await asyncio.sleep(3)

how do i get the loop to actally start
i have self.DN_cycle.start() under my cog and im getting no errors

sick birch
slate swan
hasty chasm
#

i have that

#

could it be the if check in the before loop

slate swan
#

what's the purpose of the before loop anyway?

hasty chasm
#

once a day send a message saying a day has passed in game

#

its at 3 seconds now for testing purposes

slate swan
#

yeah i get that but

#

message would never equal 1

#

did you mean to get the content of the message?

hasty chasm
#

let me edit it i changed it

#

yeah the message content

#

thats what it is now

#

the message changes so and i only want it to work when the message is true

#

which is why i have the if check in the before loop

slate swan
#

have you tried printing at any point just to debug?

hasty chasm
#

it prints the message content

slate swan
#

every 3 seconds?

hasty chasm
#

no it doesnt print anything with the loop

slate swan
#

it's not triggering then

#

you're sure the cog is loaded?

hasty chasm
#

yes

#

i also have asyncio imported so thats not it either

slate swan
#

weird

#

What's the difference in @client.command and @client.event?

hasty chasm
#

command is telling the bot to do something
event is waiting for something to happen like a person joining the server or the bot coming online

#

@slate swan

slate swan
hasty chasm
#

@slate swan i found out it stops at the line of the message fetch

radiant shuttle
#

how can i get avatal_url for a footer from a specific id

#

not the author

lyric apex
#

How to len admins in the ctx guild?

hasty chasm
#

check each member in the server see if they have the role then count += 1 each time and then print the count

lyric apex
#

By permission*

hasty chasm
#

what

lyric apex
#

You were talking about the role

lyric apex
radiant shuttle
#

how can i get avatal_url for a footer from a specific id
not the author

hasty chasm
#

idk if you can check the perms youll have to wait for someone else to answer @lyric apex

lyric apex
#

!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/latest/api.html#discord.utils.find "discord.utils.find").

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

I used member for member .... And it workedlemon_smirk

cloud dawn
#

oui

#

I'm always watching..

terse coyote
#
if arg1 == 'eng':
            if role2 in member.roles:
                emb = discord.Embed(description = f'{member.mention} **вже прийнятий та має потрібні ролі** \n {member.mention} **already accepted and has the necessary roles**', color = 0x6d41a8)
                await ctx.send(embed = emb)
                                #########################
            if roleforum or rolecur in author.roles:
            
                if ctx.channel.id == 975549648557207582:```
i need it to break after the place where # the code is
#

but idk where use break

dusk girder
#

thanks to your message i didnt have to ask my question thanks

terse coyote
#

I really don't know where to write it. no matter where I write it, it throws an error:

dusk girder
#

when my discord bot receives argument for command, it interprets the star emoji as instead of :star: which is messing up the code
should i just replace the strings with the actual emote instead of :star: or is there some way to convert the emote to the name?

#

ok it actually looks cleaner in code to use so im gonna do that

terse coyote
sick birch
#

Well the error says it. It needs to be inside of a loop, be that a for loop, a while loop

#

Though I'm not seeing why you want it

terse coyote
#

I need the code to break after

if role2 in member.roles:```
cloud dawn
#

return

terse coyote
#

why didn't it work...

sick birch
#

Can you explain what your code is trying to do? I don't fully understand

#

And knowing what it does could help me figure out what's wrong and find out if there's a better way

terse coyote
#

dm or this chat?

slate swan
#

Possible to run a command without giving all the arguments?

sick birch
sick birch
slate swan
#

how?

sick birch
# slate swan how?

!e

def function(optional=None):
  print("I am an optional function!")

function("Hello, world!")
function()
unkempt canyonBOT
#

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

001 | I am an optional function!
002 | I am an optional function!
sick birch
#

Same syntax, works with commands with no arguments

#
@bot.command()
async def optional_command(ctx: commands.Context, optional_argument=None):
  ...
regal pulsar
native root
#

so I want to automatically create a webhook that will send a message to a channel, i have this code right here ```py
@client.event
async def on_message(message):
if message.content == 'create':
await message.channel.create_webhook(name = 'hook')
await message.channel.create_webhook.send("What's up")

#

but it doesnt do anything

native root
#

nah

#

it should tho right?

slate swan
#

no

#

wait

slate swan
#

error:

#
@client.command()
async def trade(ctx, item, price, item2, price2, item3, price3, optional=None):
    await ctx.channel.purge(limit=1)
    tradeE = discord.Embed(title="{ctx.author.name} is waiting for a trade!", description="{ctx.author.mention} Is trading {item} for {price} \n {item2} - {price2} \n {item3} - {price3} \n \nAny Trade Scam Done Via This Trade Command Will Not Be Tolerated.",
    color = discord.Colour.magenta())
    tradeE.set_footer(text="Click The Button Below If You Want To Trade")
    await ctx.send(embed=tradeE, view=view23)
#

code ^

slate swan
#

of code

#

How can I implement a "only you can see this message"

#
ephemeral=True
#

after the content you sent

#

Ok thank you

#

Can I use it with embeds?

#

yes, the content can be an embed but do remember that ephemeral messages can only be sent within interactions

slate swan
slate swan
tacit storm
slate swan
#

why would you use a class over just setting its value?

haughty shore
#

Hey how can i make it so that my bot only reacts to images. so far i made a bot that reacts to specific people whenever they type but now i want to make it so it reacts only to images in a channel

#

how do i make my reaction bot only react to images?

spring flax
#

!d discord.Message.attachments

unkempt canyonBOT
spring flax
#

!d discord.Attachment.content_type

unkempt canyonBOT
slate swan
haughty shore
haughty shore
spring flax
#

you missed the :

#

but yes

slate swan
slate swan
muted dagger
#

@slate swan

slate swan
#

💀

#

well, am not gonna disagree 😂

#

that video is gold

spring flax
#

could you please send your code here in a codeblock isnteaed of as screenshots

#

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

haughty shore
#

yes i will

#
from discord.ext    import commands
from discord.ext.commands   import Bot
import asyncio
 
bot = commands.Bot(command_prefix = '//')
 
@bot.event
async def on_ready():
    print ("I have awoken")

async def react(message):
    custom_emojis = [
    ":okay:"                                                                               
    ]
    guild_emoji_names = [str(guild_emoji) for guild_emoji in message.guild.emojis]
    for emoji in custom_emojis:
        #print(emoji, guild_emoji_names)                
        #print(emoji in guild_emoji_names)
        if emoji in guild_emoji_names:
            await message.add_reaction(emoji)

@bot.event                                             
async def on_message(message):
    if message.channel.id == 929345014205653014: and \
    if message.attachment:
        await react(message)                       
spring flax
slate swan
#

comparing ids sounds like a better option

spring flax
haughty shore
slate swan
#

they would still be iterating on guild.emojis so why get the emoji again

#

¯_(ツ)_/¯

spring flax
slate swan
#

okay is not a default emoji

haughty shore
#

whenever i launch it, it just closes

slate swan
#
@client.command()
async def trade(ctx, item, price, item2, price2, item3, price3, optional=None):
    await ctx.channel.purge(limit=1)
    tradeE = discord.Embed(title="{ctx.author.name} is waiting for a trade!", description="{ctx.author.mention} Is trading {item} for {price} \n {item2} - {price2} \n {item3} - {price3} \n \nAny Trade Scam Done Via This Trade Command Will Not Be Tolerated.",
    color = discord.Colour.random())
    tradeE.set_footer(text="Click The Button Below If You Want To Trade")
    button = Button(label = "Trade", style = '3', emoji=':Pepe_Business:')
    async def button_callback(interaction):
      await interaction.response.send_message(f"Hey {ctx.author.mention} **{interaction.user.mention} has accepted your trade!")

      button.callback = button_callback
      view = View()
      view.add_item(button)
      await ctx.send(embed=tradeE, view=view)

command isnt working
my msg gets deleted but the embed isnt sent i have no on_message events

maiden fable
#

Error handler?

#

Wait I know the issue @slate swan

#

Your indent goes brrrr

haughty shore
#

anyone know why this code for my bot that reacts to images is not working?

from discord.ext    import commands
from discord.ext.commands   import Bot
import asyncio
 
bot = commands.Bot(command_prefix = '//')
 
@bot.event
async def on_ready():
    print ("I have awoken")

async def react(message):
    custom_emojis = [
    ":okay:"                                                                               
    ]
    guild_emoji_names = [str(guild_emoji) for guild_emoji in message.guild.emojis]
    for emoji in custom_emojis:
        #print(emoji, guild_emoji_names)                
        #print(emoji in guild_emoji_names)
        if emoji in guild_emoji_names:
            await message.add_reaction(emoji)

@bot.event                                             
async def on_message(message):
    if message.channel.id == 929345014205653014: and \
    if message.attachment:
        await react(message)                       
heavy shard
#

hello... i'm opening pool with aiomysql.create_pool in discord.py v2.0a setup_hook ... where should i put cleanup code? pool.close()?

slate swan
#

How do I make status to put in the bot?

slate swan
unkempt canyonBOT
#

discord.on_disconnect()```
Called when the client has disconnected from Discord, or a connection attempt to Discord has failed.
This could happen either through the internet being disconnected, explicit calls to close,
or Discord terminating the connection one way or the other.

This function can be called many times without a corresponding [`on_connect()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_connect "discord.on_connect") call.
heavy shard
#

"This function can be called many times" ... 😦

slate swan
#

yea, every time your bot "disconnects" from the API

#

which is quite rare

#

you can use on_connect to create the pool again..

maiden fable
slate swan
#

what exception is connected with this error and where i can find knowledege about this because i couldn't find this in python docs(specifically api reference):
Converting to "int" failed for parameter "amount"

maiden fable
#

Haha ik ik

slate swan
slate swan
#

!d discord.ext.commands.BadArgument

unkempt canyonBOT
#

exception discord.ext.commands.BadArgument(message=None, *args)```
Exception raised when a parsing or conversion failure is encountered
on an argument to pass into a command.

This inherits from [`UserInputError`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.UserInputError "discord.ext.commands.UserInputError")
slate swan
#

thanks

#

anyone know if its possible for my bot to pickup commands executed by other bots? (like to let other bots use commands of my bot)

#

yea sure

#

override your on_message and just add this await bot.process_commands(message)

#

tf does that mean? im not making the commands in the on message

#

im using @bot.command() etc etc

#

you can either read the docs and understand it yourself, or try to understand what other tell instead of "tf"ing it

slate swan
#

ah mhk ic

slate swan
#

commands dont work magically, they use on_message event which i just asked to "override"

#

and you got a "tf"

#

😔 ikr

slate swan
#

i was just messing 🚶‍♂️ lol

slate swan
arctic gyro
#

Hi can anyobdy tell mw the code to remove all reactions from a message

vocal snow
unkempt canyonBOT
#

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

Removes all the reactions from the message.

You need the [`manage_messages`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_messages "discord.Permissions.manage_messages") permission to use this.
slate swan
#

how can i disable a button on click?

#

after*

heady sluice
#

async def callback(self, button, interaction):
button.disabled = True
then edit the view

slate swan
#

what's the endpoint to get guild information on discord? using raw api and not a third party lib

robust fulcrum
#

Anyone help me at making a image search command pls
Me not getting good tutorial on Google

warped mirage
#

guys i need help

unkempt canyonBOT
slate swan
#

you would have to make your own asynchronous downloader though

warped mirage
#

@slate swan yo indents are fixed lol

slate swan
#

dunno

slate swan
warped mirage
#

ye

#

all my commands work but the code for level system doesnt work , can u check?

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.

warped mirage
#

ye i use it

slate swan
#

good

warped mirage
haughty shore
#

anyone know why this code for my bot that reacts to images is not working?

from discord.ext    import commands
from discord.ext.commands   import Bot
import asyncio
 
bot = commands.Bot(command_prefix = '//')
 
@bot.event
async def on_ready():
    print ("I have awoken")

async def react(message):
    custom_emojis = [
    ":okay:"                                                                               
    ]
    guild_emoji_names = [str(guild_emoji) for guild_emoji in message.guild.emojis]
    for emoji in custom_emojis:
        #print(emoji, guild_emoji_names)                
        #print(emoji in guild_emoji_names)
        if emoji in guild_emoji_names:
            await message.add_reaction(emoji)

@bot.event                                             
async def on_message(message):
    if message.channel.id == 929345014205653014: and \
    if message.attachment:
        await react(message)                       
weak horizon
#

hi, how do I connect a bot without any libraries?

slate swan
#

Is it possible to keep the built in help (cmd name) cmd and remove the default help cmd which shows all the cmds

haughty shore
worthy echo
#
@client.event
async def on_member_join(member):
    channel = client.get_channel(969946795780223056)
    embed = discord.Embed(title=f"Welcome {member}", color=discord.Colour.blue())
    await channel.send(embed=embed)```
worthy echo
tough lance
slate swan
slate swan
#

you may like to fix that using a getch

#
channel = client.get_channel(id) or await client.fetch_channel(id)
tough lance
warped mirage
worthy echo
#

why does this code not run?

@client.event
async def on_member_join(member):
    channel = client.get_channel(969946795780223056)
    embed = discord.Embed(title=f"Welcome {member}", color=discord.Colour.blue())
    await channel.send(embed=embed)
tough lance
worthy echo
heady sluice
#

show the line where you do client = commands.Bot

tough lance
#

It just checks that level or xp is present if it isn't then the code goes on else it just jump to process command

heady sluice
#

or intents = discord.Intents.default()
and everything that's related

worthy echo
heady sluice
#

no you showed this already

#

oh nah just show your code

tough lance
worthy echo
#

please help🥲

heady sluice
#

show your code 😫

tough lance
unkempt canyonBOT
#

Using intents in discord.py

Intents are a feature of Discord that tells the gateway exactly which events to send your bot. By default discord.py has all intents enabled except for Members, Message Content, and Presences. These are needed for features such as on_member events, to get access to message content, and to get members' statuses.

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

Next, in your bot you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:

from discord import Intents
from discord.ext import commands

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

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

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

warped mirage
#

I’m just so confused atm

tough lance
warped mirage
worthy echo
worthy echo
tough lance
# warped mirage What do I add in the else and if
if not xp or not level: 
    async with client.db.execute("INSERT INTO levels (level, xp, user, guild) VALUES (?, ?, ?, ?)", (0, 0, author.id, guild.id,)) as cursor:
        await client.db.commit() 
else:
    try: 
        xp = xp[0] 
        level = level[0]
    except TypeError: 
        xp = 0 
        level = 0
    #rest of the code
warped mirage
tough lance
tough lance
worthy echo
# tough lance The command should work
from discord import Intents
from discord.ext import commands

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

class CONFIG:
    TOKEN = ""
    PREFIX = "^"
    intents = intents


client = commands.Bot(command_prefix=CONFIG.PREFIX)
client.remove_command("help")

@client.event
async def on_member_join(members):
    channel = client.get_channel(977464331589545994)
    embed = discord.Embed(title=f"Welcome {members}", color=discord.Colour.blue())
    await channel.send(embed=embed)
client.run(CONFIG.TOKEN)```
THIS IS MY CODE
warped mirage
worthy echo
#

but welcome system is not work

#

please help me

tough lance
tough lance
tough lance
tough lance
#

Yes

#

Show the whole for a sec

warped mirage
#

wdym

tough lance
#

I mean show the whole code

warped mirage
#

Like in a hastebin?

tough lance
#

No a screenshot will do

warped mirage
#

Kk wait

warped mirage
#

It does this idk I need to fix something

tough lance
#

Yea I forgot about that

warped mirage
#

Ok

warped mirage
tough lance
#

This bit should be inside the if statement

warped mirage
#

Hmm ok

tough lance
#
if xp >= 100:
    level += 1
    await ctx.db #and so on
#

Along with the message line

warped mirage
#

i have this atm

tough lance
#

Ya

warped mirage
#

i tested and event doesnt work lol

#

idk lol

tough lance
#

What's the error now?

warped mirage
#

no errors

#

just nothing happes

tough lance
#

Try deleting and the db

#

File

warped mirage
#

why?

tough lance
#

Just try

tough lance
warped mirage
#

ok so level.db gets deleted?

tough lance
#

Yes

#

It'll readd automatically

warped mirage
#

now what?

#

@tough lance

tough lance
#

Try the event and see if it gets added in the db

warped mirage
#

OH

#

level.db was auto added

warped mirage
#

If I take them out of the if statement it works but it’s broken

slate swan
warped mirage
#

im tryna code it with a rank card but idk

#

if yall can help i dont mind

slate swan
#

you could take a look though "maybe"

warped mirage
#

can yall help me add a rank card to it?

slate swan
slate swan
#

and it worked fine

warped mirage
#

what database do u use?

slate swan
#

sqlite

warped mirage
#

ok

#

wait @slate swan do i copy ur database or what lmao

#

theres no level thing

slate swan
#

I just told you to refer not copy 😭

paper sluice
#

xD

slate swan
#

plus its a whole lot different

warped mirage
#

lmao i just wanna fix my damn shit , help me out

#

xD

slate swan
#

smh

warped mirage
#

anyone down to help or not 👀

slate swan
warped mirage
#

bruh

slate swan
warped mirage
#

scroll up

slate swan
#

i see

#

first of all

#

pfftttt

#

the code's so messy

#

how did you even think of it...

warped mirage
#

idk

desert cosmos
#

can someone here helpp

warped mirage
desert cosmos
#

i am stuck with second code of my bot

#

like we can use 2 different codes for same bot on different machine right ?

formal basin
#

Anyone know how to make a tiktok notification bot?

desert cosmos
formal basin
shrewd apex
shrewd apex
shrewd apex
#

very simple for beginners

desert cosmos
#

so i am trying to run separate codes on different machines

#

but with same bot id

shrewd apex
#

nope not possible

#

the first build will get overwritten by the second build

desert cosmos
desert cosmos
#

it sends events to machine which is running code

shrewd apex
#

it's same as can u have 2accs to the same userid

desert cosmos
#

and discord allow multiple logins with same token

desert cosmos
formal basin
shrewd apex
#

hmm intresting

formal basin
desert cosmos
#

yup

#

but only events are working

formal basin
#

Idk what I can do?

desert cosmos
#

not commands

shrewd apex
#

what are ur events?

desert cosmos
#

on_message

shrewd apex
#

u have process_commands on that right?

desert cosmos
#

oh no

#

do we have to do that ?

shrewd apex
#

-_-

#

yeah

desert cosmos
#

i don't have it in first code

shrewd apex
#

await bot.process_commands(message)

desert cosmos
#

message 🙃 why ?

desert cosmos
shrewd apex
#

on_message(message)

desert cosmos
shrewd apex
#

on message will intercept the command

desert cosmos
#

but @commands.command() not working

shrewd apex
#

u need a process command to make it work

desert cosmos
#

got it

#

many thanks

shrewd apex
#

np i learned something new too

desert cosmos
slate swan
desert cosmos
#

it need changes like ctx.send to ctx.channel.send

shrewd apex
#

yeah but on message event always occurs before the command acts so if u add a return in on message ur commands will fail

desert cosmos
slate swan
shrewd apex
slate swan
#

smh

shrewd apex
#

😂

knotty agate
#

is there any way i can get the channel id from a message? something like

channel_id = message.channel.get_id()
desert cosmos
shrewd apex
knotty agate
#

thanks

slate swan
#

trying to start discord task but I get zis error discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'coroutine' object has no attribute 'start'

#

well

#

show code.

#

5 sec

heady sluice
#

didn't use deco

#

I'm calling it

slate swan
#

I did

#
@tasks.loop(seconds=10)
async def testloopyuwu(joe):
  if joe:
    print('joe')

@client.command()
async def joemama(ctx):
  testloopyuwu(True)
heady sluice
#

uh

slate swan
#

🚶‍♂️ tasks, dont take args like this

heady sluice
#

what does loop turn the func into

#

!d discord.ext.tasks.loop

unkempt canyonBOT
#

discord.ext.tasks.loop(*, seconds=..., minutes=..., hours=..., time=..., count=None, reconnect=True)```
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/latest/ext/tasks/index.html#discord.ext.tasks.Loop "discord.ext.tasks.Loop").
slate swan
#

wot

#

a loop

#

L

heady sluice
#

what loop

heady sluice
#

!d discord.ext.tasks.Loop.start

unkempt canyonBOT
slate swan
heady sluice
#

call this

slate swan
#

how take args

#

you need to pass them inside the start method

heady sluice
#

testloopyuwu.start(True)

slate swan
#
@loop(m=1)
async def foo(arg):
  ...

foo.start("arg")
#

o

heady sluice
#

please give your tasks a bit of respect with names

#

😔

slate swan
#

uwu

#

uwu >~<

#

UwU

slate swan
#

wait, how 2 run a task multiple times?

#

I want them to be like threads

#

running constantly untill users wants them stopped

exotic maple
#

How would i add this? Does anyone know the documentation if any

slate swan
exotic maple
#

cool thanks

slate swan
jagged adder
#

im trying to use the 'random' api, can someone tell me how to take the output and print a different reply depending on what the randomized output is? thought it might be as simple as an if command but idk how to apply it

slate swan
#

like reply w/ a completley random string?

jagged adder
#

idk how to paste as code but this is what i got sec

#

if message.content.upper() == "A":
random.choice(LOOTED_CHEST_RANDOMIZER)
if [1, 2]:
message.channel.send("slip and fall")

#

using an item list on the randomizer

#

im experimenting atm to see what works

slate swan
#

Does anyone have a slight clue on whenever I run my bot, it tells me to enable intents, so I do but then it just breaks my bot entirely and throws no errors

jagged adder
jagged adder
#

the list is 1 thru to 6

slate swan
#

if 1 then slip and fall else

slate swan
jagged adder
slate swan
jagged adder
#

im trying to create several chance outputs, only got the 1 in there so far. ie, 1 or 2 causes x, 3 or 4 causes y, etc

slate swan
#
number = 1

if number == 1:
  print("The number is 1")
elif number == 2:
  print("The number is 2")
else:
  print("The number is unknown")
jagged adder
#

want a total of 4 diff outputs depending on the 'dice roll'

#

how do i apply that to the current tho? would i still be drawing from a list?

slate swan
#

Can you send me your script?

jagged adder
#

ie could i put that below the current part

tidal talon
heavy shard
#

also, your bot token leaked, you're gonna need to regenerate it

tidal talon
#

this is an obsolete token

heavy shard
#

ok

tidal talon
#

removed = but did not help

heavy shard
#

it should be os.getenv("TOKEN")

tidal talon
#

did not help

heavy shard
#

you also need to set environment variable "TOKEN" to your token... or use a different metod to load token value

tidal talon
#

with variable order, complains about syntax

#

AttributeError

#

'NoneType' object has no attribute 'strip'

robust fulcrum
#

Can anyone help me how to use @unkempt canyon is our bot pls
Me dont know how to use dockerfile

past onyx
#

i need help

#

petpet gif isnt working on linux

#
May 21 14:01:40 Lab1 bash[2497]:     await func.invoke(ctx, **args)
May 21 14:01:40 Lab1 bash[2497]:   File "/home/pi/.local/lib/python3.9/site-packages/discord_slash/model.py", line 210, in invoke
May 21 14:01:40 Lab1 bash[2497]:     return await self.func(*args, **kwargs)
May 21 14:01:40 Lab1 bash[2497]:   File "/home/pi/Bot/main.py", line 427, in petpet
May 21 14:01:40 Lab1 bash[2497]:     from petpetgif import petpet # import petpetgif
May 21 14:01:40 Lab1 bash[2497]:   File "/home/pi/.local/lib/python3.9/site-packages/petpetgif/petpet.py", line 1, in <module>
May 21 14:01:40 Lab1 bash[2497]:     from PIL import Image
May 21 14:01:40 Lab1 bash[2497]:   File "/home/pi/.local/lib/python3.9/site-packages/PIL/Image.py", line 134, in <module>
May 21 14:01:40 Lab1 bash[2497]:     if __version__ != getattr(core, "PILLOW_VERSION", None):
May 21 14:01:40 Lab1 bash[2497]: NameError: name 'core' is not defined
pure crypt
#

how can i get the status from a user

slate swan
unkempt canyonBOT
#

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

or was it members intent idk

slate swan
keen moth
#

!e

unkempt canyonBOT
#
Missing required argument

code

hoary cargo
slate swan
#

Anyone got a clue that my bot suddenly started needing intents enabled and since I enabled it my bot just does not run any command, and it does not error anything, so I literally do not know how I can fix it

#
@client.command()
@commands.is_owner()
async def load(ctx, extension):
  await client.load_extension(f"cogs.{extension}")
  print(f'loaded {extension}')

cog aint loaded no errors neitheris there something printed in terminal

keen moth
#

!e while True: pass

slate swan
slate swan
#

Is that bad or?

slate swan
#

intents.message_content = True

#

yes

#

Alright

slate swan
keen moth
#

Ok

slate swan
slate swan
#

1 is printed

#

Error I get is
Exception has occurred: ExtensionNotFound

#

well, that file does not exist then.

#

But

#

show your file structure

formal basin
#
 @tasks.loop(seconds=30)
async def checkforvideos():
  with open("youtubedata.json", "r") as f:
    data=json.load(f)
  
  
  print("Now Checking!")

  for youtube_channel in data:
    print(f"Now Checking For {data[youtube_channel]['channel_name']}")
    
    channel = f"https://www.youtube.com/channel/{youtube_channel}
    html = requests.get(channel+"/videos").text

    
    try:
      latest_video_url = "https://www.youtube.com/watch?v=" + re.search('(?<="videoId":").*?(?=")', html).group()
    except:
      continue

    if not str(data[youtube_channel]["latest_video_url"]) == latest_video_url:

     
      data[str(youtube_channel)]['latest_video_url'] = latest_video_url

      with open("youtubedata.json", "w") as f:
        json.dump(data, f)

 
      discord_channel_id = data[str(youtube_channel)]['notifying_discord_channel']
      discord_channel_id = client.get_channel(int(discord_channel_id))

     
      msg = f"<@&976169188274086019> {data[str(youtube_channel)]['channel_name']} Just Uploaded A Video Or He is Live Go Check It Out: {latest_video_url}"

      await discord_channel_id.send(msg)

checkforvideos.start()


@checkforvideos.before_loop
async def checkforvideos():
  print('waiting... 2 ')
  await client.wait_until_ready()


@slash.slash(name="add_youtube_notification", description="admin only")
@commands.has_permissions(manage_roles=True)
async def add_youtube_notification(ctx, channel_id: str, *, channel_name: str):
  with open("youtubedata.json", "r") as f:
    data = json.load(f)
  
  data[str(channel_id)]={}
  data[str(channel_id)]["channel_name"]=channel_name
  data[str(channel_id)]["latest_video_url"]="none"

  #you can also get discord_channe id from the command 
  #but if the channel is same then you can also do directly
  data[str(channel_id)]["notifying_discord_channel"]="975360118591991818"

  with open("youtubedata.json", "w") as f:
    json.dump(data, f)

  await ctx.send("Added Your Account Data!") ```
slate swan
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.

formal basin
slate swan
#

you have a folder cogs, inside it you have another folder named cogs, then you have antiswear inside that one

#

Yes

#

did you do !load cogs.antiswear?

#

I did ,load antiswear

#

Thats wrong

slate swan
#

yea, try this

flat solstice
#

Can someone check this code? I can't seem to get it to work, I have enabled voice-state Intents and loaded the cog but it's not kicking me from the afk channel but I'm also not getting any errors unless my error handler is eating it (which I don't think is likely). The code is here https://paste.pythondiscord.com/rorenuxega because it's so long

slate swan
#

kk

formal basin
formal basin
#

, , ,hi, , ,

slate swan
#

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

slate swan
#

they are backticks

hoary cargo
#

i assume you are on phone

formal basin
slate swan
#

phone has backticks too, atleast for me

hoary cargo
slate swan
#

it does for every keyboard....

slate swan