#discord-bots

1 messages ยท Page 1138 of 1

tacit aspen
#

o i saw that on stack overflow but didn't understand thanks for explaining pithink

umm but can u tell me a way to read the documentation or a source that tells how to in general read documentation

placid skiff
#

d.py docs is pretty clear D_D

vocal snow
#

Corey Schafer has a good set of videos on OOP on YouTube if you're interested

tacit aspen
slate swan
#
@bot.command()
async def timeout(ctx, user: discord.Member=None, time=None, *, reason=None):
  time = humanfriendly.parse_timespan(time) 
  await user.timeout(until = discord.utils.utcnow() + datetime.timedelta(seconds=time), reason=None)  
  await ctx.send(f"Timedout.")```
vocal snow
slate swan
#

thats what im using

loud junco
vocal snow
#

No, you're importing datetime from datetime

slate swan
# loud junco show full traceback? like the fulll error
Traceback (most recent call last):
  File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 181, in wrapped
    ret = await coro(*args, **kwargs)
  File "c:\Users\user\Desktop\Discord Bot\Foxx\main.py", line 726, in timeout
    await user.timeout(until = discord.utils.utcnow() + datetime.timedelta(seconds=time), reason=None)
AttributeError: type object 'datetime.datetime' has no attribute 'timedelta'

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

Traceback (most recent call last):
  File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\bot.py", line 360, 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 927, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 190, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: type object 'datetime.datetime' has no attribute 'timedelta'```
vocal snow
#

Either ```py
import datetime

datetime.timedelta
orpy
from datetime import timedelta

timedelta

slate swan
#

okay thanks

#

it says its missing permissions now??

loud junco
#

admin permission

slate swan
#

it does

vocal snow
#

The bot's top role needs to be higher than the target user's top role

slate swan
#

oooh

vocal snow
#

And I would recommend not giving your bot admin permissions, only give it what it needs

scenic grove
#

!e print('a')

unkempt canyonBOT
#

@scenic grove :white_check_mark: Your eval job has completed with return code 0.

a
scenic grove
#

wow cool

loud junco
#

it has always been ๐Ÿคฃ

scenic grove
loud junco
supple cobalt
#

got a question

#

if i let a bot do tons of commands, will it have a disadvantage?

paper sluice
supple cobalt
#

like could i add and add commands for the bot to do?

paper sluice
#

there is no limits to how many commands you can have

supple cobalt
#

o

#

YAYA

paper sluice
#

the only limit would be your processor, which i doubt you will ever cross

supple cobalt
#

ok nvm<3

#

i have an i7 10th generation so i actually don't think it will keep tbh

paper sluice
#

huh?

austere gust
#

yo

#

yesterday with the help of @torn sail we made this code

bot.embeds = {}

@bot.command()
async def mdc(ctx):
    embed = discord.Embed(colour=0x0000FF)
    embed.add_field(name='Nรฉv', value='โ€', inline=True)
    embed.add_field(name='Indok', value='โ€', inline=True)
    embed.add_field(name='Dรกtum', value='โ€', inline=True)
    ctx.bot.embeds[ctx.author.id] = embed
    
    await ctx.send(embed=embed)

@bot.command()
async def addmdc(ctx, namee, reason, date):
    embed = ctx.bot.embeds[ctx.author.id] 
    fields = embed.fields
    fields[0].value += namee  # or whatever your variable is called
    #now we can do the same thing for your other arguments
    fields[1].value += reason
    fields[2].value += date```
paper sluice
austere gust
#

The mdc message sends this which is good.

supple cobalt
#

YAYA

austere gust
#

and if I run addmdc yo yo yo , then run mdc agaian

#

yo yo yo will appear

#

but this isn't working

spring flax
slate swan
#

imagine accessing bot through a property when you have the direct access to the bot

#

what's the issue?

robust fulcrum
#

I started making custom prefix again

#
import aiosqlite
import discord
from discord.ext import commands
import asyncio

def get_prefix():
    pass

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

async def connect():
    connect = await aiosqlite.connect('prefixes.db')
    cursor = await connect.cursor()
    await cursor.execute('CREATE TABLE IF NOT EXISTS prefixes(guild_id INTEGER,prefix TEXT)')
    await connect.commit()
    await connect.close()

@bot.event
async def on_ready():
    print("ready")
    await connect()
#

I not able to understand what should be args in get prefix

robust fulcrum
slate swan
#

I'm totally out since on_ready

robust fulcrum
#

Hmmmm

robust fulcrum
slate swan
#

setup_hook

robust fulcrum
#

That's a hard thing for me

robust fulcrum
slate swan
#

and create a global connection

#

yes?

robust fulcrum
slate swan
# robust fulcrum How can I create global conn?
async def connect():
  bot.conn = await aiosqlite.connect(...)
  cursor = await bot.conn.cursor()
  await cursor.execute("DO TABLE CREATION CRAP HERE")
  await bot.conn.commit()

now bot.conn is global

slate swan
#

setup

#

how can i check
if ctx.auther id in Mod.txt:

loud junco
#

and what is Mod.txt

slate swan
loud junco
slate swan
#

!d open

unkempt canyonBOT
#

open(file, mode='r', buffering=- 1, encoding=None, errors=None, newline=None, closefd=True, opener=None)```
Open *file* and return a corresponding [file object](https://docs.python.org/3/glossary.html#term-file-object). If the file cannot be opened, an [`OSError`](https://docs.python.org/3/library/exceptions.html#OSError "OSError") is raised. See [Reading and Writing Files](https://docs.python.org/3/tutorial/inputoutput.html#tut-files) for more examples of how to use this function.

*file* is a [path-like object](https://docs.python.org/3/glossary.html#term-path-like-object) giving the pathname (absolute or relative to the current working directory) of the file to be opened or an integer file descriptor of the file to be wrapped. (If a file descriptor is given, it is closed when the returned I/O object is closed unless *closefd* is set to `False`.)
slate swan
#

read the txt file using this

#

@slate swan help ๐Ÿ˜”

#

oh wait no
dont help

slate swan
#

I'm being a dick

#

lmao got it

winter gull
#

Alrr

#

I wanted to ask if we can use @client.listen() or @client.event and @client.command() because for me the command does not seem to works whenever I try. Tho the event listening is working just fine.

The client is the instance of discord.commands.Bot() and the prefix is also saved in a json file.

paper sluice
# winter gull Alrr

on_guild_channel_create is an event, so it will be triggered automatically when that function is decorated with bot.event or bot.listen()

cursive spindle
#
file: main.py
CONFIG_JSON_PATH = "D:\[BOT DISCORDV2.0]\Discord Bot 2.0"
Cog File
#

how i can import CONFIG_JSON_PATH in my cog file?

slate swan
#

from main import CONFIG

cursive spindle
paper sluice
#

if yes, then you should put such data in a different file, depending on when you load your cog, you might have a circular import issue

paper sluice
#

no another file next to ur main file

#

like utils.py where you have objects which ur cogs might use

#

so in ur cog u can do from utils import ... and the same thing in ur main.py

cursive spindle
#

ok

slate swan
#
     channel = await interaction1.guild.create_text_channel(f"mm-{interaction1.user.name}", topic=f"{guild.name} | Request ID: {numbergen}", category=category, overwrites=overwrites)```
error:
```Traceback (most recent call last):
  File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ui\view.py", line 371, in _scheduled_task
    await item.callback(interaction)
  File "c:\Users\user\Desktop\Ayu Bot\main.py", line 250, in button_callback1
    channel = await interaction1.guild.create_text_channel(f"mm-{interaction1.user.name}", topic=f"{guild.name} | Request ID: {numbergen}", category=category, overwrites=overwrites)
  File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\guild.py", line 1170, in create_text_channel
    data = await self._create_channel(
  File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\guild.py", line 1051, in _create_channel
    "id": target.id,
AttributeError: 'NoneType' object has no attribute 'id'```
slate swan
#

category = discord.utils.get(guild.categories, name='mm tickets')

robust fulcrum
potent spear
torn sail
austere gust
vocal snow
slate swan
vocal snow
dapper thistle
#

Would it be possible

#

To make a discord bot. That with a command. Puts their phone number ( That they would input ) and their discord name & # into a .csv file?

slate swan
vocal snow
slate swan
#

i dont..

vocal snow
#

Then do

slate swan
#

but id prefer to sort out my error first

#

and checking if the category is None isnt really useful for what im coding

dapper thistle
vocal snow
#

no

dapper thistle
#

Could I get some help?

slate swan
#

!rule 7

unkempt canyonBOT
#

7. Keep discussions relevant to the channel topic. Each channel's description tells you the topic.

slate swan
#

it's a replit issue soooo

paper sluice
#

TIL there is a replit server

dapper thistle
#

Any documentation on how to make discord bots?

slate swan
#

I think I should make a starter guide ๐Ÿ˜”

#

lucas

#

I agree

#

i mean the hikari series is not bad at all other than the token leaks

river rain
#

Hi, im trying to make a discord.py economy bot with some commands, such as a rob command.

I want there to be a cooldown on the rob command, but this cooldown seems to always be activated when I use @commands.cooldown(...), but this is not what I want;
if the robbing fails for whatever reason (not enough arguments, person can not be robbed, etc), I do not want the cooldown to start.

Is this possible?

torn sail
#

This pin needs to be updated

slate swan
#

broken docs link

#

yeah the docs are now in the latest branch, not master

slate swan
slate swan
#

i found his github somehow

slate swan
paper sluice
#

?

winter gull
#

but when i am using @bot.command

#

it does not respond when the command is called

#

also

@bot.listen()
async def on_message(message):
    print(str(message.content))
#

this is just giving me an empty string

#

or \n i guess

slate swan
#

Did u enabled intents

paper sluice
#

commands are only called by users

winter gull
#

yes

#

that is the issue, when i am calling the command

#

it is not responding

winter gull
shrewd apex
#

yes and in ur dev page

winter gull
#

alright

paper sluice
winter gull
slate swan
#

do you have an on_message event

winter gull
cloud dawn
#

How big is this bot?

winter gull
#

its a small bot

cloud dawn
#

Could you maybe just paste the whole bot here ->

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.

cloud dawn
#

Leave out the token.

slate swan
#

you can even include it if you want us e to use your token

winter gull
slate swan
winter gull
#

i use .env for keeping my token lmao

slate swan
winter gull
paper sluice
#

bruh

cloud dawn
#

xD

slate swan
#

!intents member_content = True, instead og members= True thats it

unkempt canyonBOT
#

Using intents in discord.py

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

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

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

from discord import Intents
from discord.ext import commands

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

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

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

slate swan
cloud dawn
#

He/she only needs the guild intent for on_guild_channel_create

winter gull
#

alright, i have seen it and it worked for me. The issue for this code is the ping command is not working when there is a @bot.listen() specified

cloud dawn
slate swan
#

wow panda ;-;

cloud dawn
#

I have a slash bot with 0 intents and can just run a simple ping cmd.

slate swan
#

its a normal message comamnd tho?

cloud dawn
#

Yeah true.

slate swan
#

which ofc needs message_content intents to work

cloud dawn
#

My mind do be slash

paper sluice
#

to use prefix commands, the bot needs to read messages, to read messages it needs message_content intent

cloud dawn
#

I just got up okay

paper sluice
#

๐Ÿ‘

winter gull
#

@slate swan

cloud dawn
slate swan
winter gull
paper sluice
winter gull
#

ahh

#

tysm it works perfectly

slate swan
paper sluice
slate swan
paper sluice
#

๐Ÿ˜ถ

pliant pagoda
#

anyone know how i could send a message in a logs channel when i kick using a command?
code:

@bot.command()
@commands.has_permissions(kick_members=True)
async def kick(ctx, member: discord.Member, *, reason=None):
    if reason==None:
      reason=" no reason provided"
    await ctx.guild.kick(member)
    await ctx.send(f'User {member.mention} has been kicked for {reason}',delete_after=3.0)
winter gull
#

i wish i could, i am just finishing up what i am doing rn

#

but sure

slate swan
#

ash bully

winter gull
leaden hollow
#

so just update dpy to the latest github version
getting this error

  File "d:\Primary\HawT\main.py", line 58, in <module>
    asyncio.run(start())
  File "C:\Program Files\Python310\lib\asyncio\runners.py", line 44, in run
    return loop.run_until_complete(main)
  File "C:\Program Files\Python310\lib\asyncio\base_events.py", line 646, in run_until_complete
    return future.result()
  File "d:\Primary\HawT\main.py", line 56, in start
    await bot.run(TOKEN)
  File "D:\Primary\HawT\venv\lib\site-packages\discord\client.py", line 872, in run
    asyncio.run(runner())
  File "C:\Program Files\Python310\lib\asyncio\runners.py", line 33, in run
    raise RuntimeError(
RuntimeError: asyncio.run() cannot be called from a running event loop
sys:1: RuntimeWarning: coroutine 'Client.run.<locals>.runner' was never awaited```
cloud dawn
#

What are you trying to do?

#

More specific.

#

Get all the leaders of the teams?

#

So all team leaders?

#

Or anyone with the role "Franchise Owner"?

#

Does that member have a role with the team name?

#

So the FO has like "Arizona Cardinals" as a role?

#

okay I can work with that.

slate swan
pliant pagoda
#
@bot.command()
@commands.has_permissions(kick_members=True)
async def kick(ctx, member: discord.Member, *, reason=None):
    if reason==None:
      reason=" no reason provided"
    await ctx.guild.kick(member)
    await ctx.send(f'User {member.mention} has been kicked for {reason}',delete_after=3.0)

Hi๐Ÿ™‚
Two questions, how could i make it send a message to a logs channel when a kick is done? And how could i delete the command usage message?

slate swan
#

how to split multiline text in an argument?

winter gull
pliant pagoda
#

thank you

slate swan
slate swan
cloud dawn
#
@bot.slash_command(name="folist")
async def folist(interaction):
    teams = [
        "Arizona Cardinals", "Atlanta Falcons", "Baltimore Ravens",
        "Buffalo Bills", "Carolina Panthers", "Chicago Bears",
        "Cincinnati Bengals", "Cleveland Browns", "Dallas Cowboys",
        "Denver Broncos", "Detroit Lions", "Green Bay Packers",
        "Houston Texans", "Indianapolis Colts", "Jacksonville Jaguars",
        "Kansas City Chiefs", "Las Vegas Raiders", "Los Angeles Chargers",
        "Los Angeles Rams", "Miami Dolphins", "Minnesota Vikings",
        "New England Patriots", "New Orleans Saints", "New York Giants",
        "New York Jets", "Philadelphia Eagles", "Pittsburgh Steelers",
        "San Francisco 49ers", "Seattle Seahawks", "Tampa Bay Buccaneers",
        "Tennessee Titans", "Washington Commanders"
    ]
  
    fo = nextcord.utils.get(interaction.guild.roles, name="Franchise Owner")
    desc = ""

    for fomember in fo.members:
        team = list(filter(lambda r: True if r.name in teams else False, fomember.roles))[0].name
        emoji = nextcord.utils.get(interaction.guild.emojis, name=team.replace(" ", "_"))
        desc += f"{emoji} - {fomember.mention} in {team}\n"

    embed = nextcord.Embed(
        title="Franchise Owners",
        colour=0xFFF
        description=desc
    )

    await interaction.send(embed=embed)
#

edited

#

The code

#

I did do It right I thought for a sec it returned a role obj

#

hmm lambda condition is wrong 1 sec

#

Try now

#

I do recommend getting a better solution for it all.

#

Since it is pretty hard coded at the moment.

#

Sure how would you like it?

#

What is rostercap?

slate swan
#

does anyone have code for a example of a linkbutton?

cloud dawn
#
@bot.slash_command(name="folist")
async def folist(interaction):
    teams = [
        "Arizona Cardinals", "Atlanta Falcons", "Baltimore Ravens",
        "Buffalo Bills", "Carolina Panthers", "Chicago Bears",
        "Cincinnati Bengals", "Cleveland Browns", "Dallas Cowboys",
        "Denver Broncos", "Detroit Lions", "Green Bay Packers",
        "Houston Texans", "Indianapolis Colts", "Jacksonville Jaguars",
        "Kansas City Chiefs", "Las Vegas Raiders", "Los Angeles Chargers",
        "Los Angeles Rams", "Miami Dolphins", "Minnesota Vikings",
        "New England Patriots", "New Orleans Saints", "New York Giants",
        "New York Jets", "Philadelphia Eagles", "Pittsburgh Steelers",
        "San Francisco 49ers", "Seattle Seahawks", "Tampa Bay Buccaneers",
        "Tennessee Titans", "Washington Commanders"
    ]
  
    fo = nextcord.utils.get(interaction.guild.roles, name="Franchise Owner")
    desc = ""

    for fomember in fo.members:
        team = list(filter(lambda r: True if r.name in teams else False, fomember.roles))[0].name
        member_count = len(nextcord.utils.get(interaction.guild.roles, name=team).members)
        emoji = nextcord.utils.get(interaction.guild.emojis, name=team.replace(" ", "_"))
        desc += f"{fomember.mention} - {emoji} `{member_count}/24`\n"

    embed = nextcord.Embed(
        title="Franchise Owners",
        colour=0xFFF
        description=desc
    )

    await interaction.send(embed=embed)
slate swan
#

How to pass a multiline text to the argument?

cloud dawn
#
text = "line 1\nline 2\n line 3"
slate swan
#

hmm i try

paper sluice
cloud dawn
#

!e !e ```py
def pretty_text(text: str) -> str:
return "\n".join([x.strip() for x in text.splitlines()])

print(pretty_text("""
line 1
line 2
line 3
"""))

unkempt canyonBOT
#

@cloud dawn :white_check_mark: Your eval job has completed with return code 0.

001 | 
002 | line 1
003 | line 2
004 | line 3
cloud dawn
#

Hmm first line is weird doesn't happen on my ide

pliant pagoda
#
@bot.command()
async def announce(ctx, channel: discord.TextChannel, *, text=None):
  if text==None:
    text="no text provided"
    await channel.send(f'{text}')

No error or anything, just wont do what its meant to do. Any ideas?๐Ÿค”

slate swan
slate swan
slate swan
cloud dawn
slate swan
#

you can interaction.channel.send and interaction.response.defer() but I don't see a point of doing that

slate swan
#

await ctx.send(embed=embed,veiw=(discord.ui.Button(label='link', url=link)))
trying to do somthing like this

#

.

slate swan
cloud dawn
slate swan
#

I don't get why people use Role names instead of IDs

#

IDs are much more convenient

#

F U N

slate swan
#

i forgor

slate swan
#

ofcourse it is

#

imagine having 2 roles with same names

#

utils.get will return a list in that case iirc

#

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

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

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

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

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

just make your own custom getter

slate swan
flint isle
#

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

slate swan
#

there's already a commands.RoleConverter

cloud dawn
#

jUsT uSe sLaSh

slate swan
flint isle
#

code:
https://paste.pythondiscord.com/ofakiwilun
error:

Bot is ready!
Waiting For Commands
Ignoring exception in command download:
Traceback (most recent call last):
  File "C:\Users\Andy\AppData\Local\Programs\Python\Python310\lib\site-packages\disnake\ext\commands\core.py", line 172, in wrapped
    ret = await coro(*args, **kwargs)
  File "C:\Users\Andy\PycharmProjects\WhiskeyBotMain\cogs\youtube.py", line 42, in download
    file_size = os.stat(f"{file_name}").st_size
OSError: [WinError 123] The filename, directory name, or volume label syntax is incorrect: "I Built The World's Tallest Dice Tower (But Does It Survive?!).mp4"```
cloud dawn
#

!ytdl

unkempt canyonBOT
#

Per Python Discord's Rule 5, we are unable to assist with questions related to youtube-dl, pytube, or other YouTube video downloaders, as their usage violates YouTube's Terms of Service.

For reference, this usage is covered by the following clauses in YouTube's TOS, as of 2021-03-17:

The following restrictions apply to your use of the Service. You are not allowed to:

1. access, reproduce, download, distribute, transmit, broadcast, display, sell, license, alter, modify or otherwise use any part of the Service or any Content except: (a) as specifically permitted by the Service;  (b) with prior written permission from YouTube and, if applicable, the respective rights holders; or (c) as permitted by applicable law;

3. access the Service using any automated means (such as robots, botnets or scrapers) except: (a) in the case of public search engines, in accordance with YouTubeโ€™s robots.txt file; (b) with YouTubeโ€™s prior written permission; or (c) as permitted by applicable law;

9. use the Service to view or listen to Content other than for personal, non-commercial use (for example, you may not publicly screen videos or stream music from the Service)
flint isle
slate swan
cloud dawn
#

It's neither.

slate swan
#

panda you so smart ๐Ÿ˜”

cloud dawn
#

Can't tell if sarcasm or not ๐Ÿ˜‚

slate swan
#

if I say that's sarcastic you're gonna be offended
either way sucks works

slate swan
upper belfry
#

One Library Ik u might need can be datetime

cold needle
#

hi

#

i made a command

#
@bot.command()
async def hi(ctx, *, args=None):
    if args != None:
        members = ctx.guild.members
       
        for member in members:
               print(member)```
#

but it just prints the name of the dc bot

#

and not of eg me

slate swan
#

Check this

cold needle
#
intents.typing = False
intents.presences = False```
#

but still dont work

slate swan
#

Have you enabled them in the application webpage

torn sail
cold needle
torn sail
#

intents.members = True

cold needle
#

worked

#

thx

upper belfry
#

what is the difference between ctx.send() and ctx.channel.send()?

slate swan
#

Same thing

pliant pagoda
#
#ban command
@bot.command()
@commands.has_permissions(ban_members=True)
async def ban(ctx, member: discord.Member, *, reason=None):
    LogsChannel = discord.utils.get(ctx.guild.channels, name="logs")
    if reason==None:
      reason="no reason provided"
    await ctx.message.delete()
    await ctx.guild.ban(member)
    await ctx.send(f'User {member.mention} has been banned. Reason: {reason}',delete_after=3.0)
    await LogsChannel.send(f"{member.mention} has been banned. Reason: {reason}")

Do you know how i could dm the user being banned?

slate swan
#

Do it before ban

#

And Iโ€™m pretty sure itโ€™s user.send()

pliant pagoda
#

lol

slate swan
#

!d discord.Member.send

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

Sends a message to the destination with the content given.

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

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

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

thought it's be more complicated than that๐Ÿ˜…

#

Thanks

safe obsidian
pliant pagoda
#

yeah, thought about that but oh well๐Ÿ˜…

#

so before the ban i should put: await send(content)

#

or does it have to be all of that๐Ÿง

gilded lichen
#

hello

#

help me python bot discord?

slate swan
#

Yes

gilded lichen
#

private

slate swan
#

No

indigo pilot
#

Hey, does anyone have a idea to do a check for this?

im not sure if im dumb but, for all my commands i need to a check if the userdict dosnt exist, it makes it because i have checks in the start of the command that need to check the dict. if i ever edit the dict tho ill have to gothru every single command and edit where it makes the dict

is there any way i can just have a single check for all cmds(slash) and if it dosnt exist it would just maybe like, return a msg saying run the cmd again & during that it makes the dict? idk haha

slate swan
#

Make a command decorator for it

crude crater
#

Why is it that I get an "Invalid two-factor code" when I try to invite my bot to my server?

#

Not Python related but I just need help with ma Discord bot

slate swan
#

Unrelated so I will not help you ( not that I donโ€™t have a clue how to help you haha ๐Ÿ˜… )

pliant pagoda
#

'Unindent does not match any outer indentation level' ๐Ÿง

crude crater
#

I could be wrong but I think that's why

slate swan
#

Yeah thereโ€™s a indent

crude crater
#

Like how you have two "await", I'm pretty sure it's supposed to line up

slate swan
crude crater
#

Fr you gotta get rid of dat shit bruh ๐Ÿ™

slate swan
#

Ong

crude crater
#

That shit'll fuck up your code frfr

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

Sends a message to the destination with the content given.

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

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

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

Fr lmao

#

Just make one ๐Ÿคทโ€โ™‚๏ธ

slate swan
#

๐Ÿ’€

crude crater
#

๐Ÿ’ฏ

slate swan
#

wtf has happened

slate swan
#

Can people need help

#

Iโ€™m bored

dusty tree
#

need sum help

slate swan
#

is there a way to add discord user variable to on_button_click event?

slate swan
slate swan
#

i want a discord user

#

like the parameter for command (user:discord.User)

#

Oh

#

You can add a drop down view with all server members

#

Or an input view

#

Button is purely a clickable button

dense coral
#
with open('voice.json', 'r') as file:
        voice_data = json.load(file)
        new_user = str(member.id)

        # Update existing user
    if new_user in voice_data:
        voice_leave_time = int(datetime.datetime.now().timestamp())
        voice_join_time = voice_data[new_user]

        calculate_time = (
                datetime.datetime.timestamp(voice_leave_time) - datetime.datetime.timestamp(
            voice_join_time))

        voice_data[new_user] = f'{calculate_time}'

        with open('voice.json', 'w') as update_user_data:
            json.dump(voice_data, update_user_data, indent=4)

        # Add new user
    else:
        new_voice_join_time = int(datetime.datetime.now().timestamp())
        voice_data[new_user] = new_voice_join_time

        with open('voice.json', 'w') as new_user_data:
            json.dump(voice_data, new_user_data, indent=4)```
did you know?
slate swan
#

You are trying to convert a timestamp to an int

#

And obviously it doesnโ€™t like that

torn sail
dense coral
#

Ok, I check it

#

thanks!

torn sail
dense coral
#

oh ok

rancid vine
#

Why does this come up when i try to invite it

slate swan
#

Share screen

#

@rancid vine

rancid vine
#

nvm

#

i fixed it

wild spoke
#

For some reason when I try to import praw, project can't find it

#

but I installed it using cmd

#

pls help

potent spear
crude crater
#

to make a leave command, how would i write the guild id inside of the parentheses??

#

async def leave(ctx, ):

#

what do i put after ctx?

#

so i can put the id of the server to leave and the bot will leave

cloud dawn
crude crater
cloud dawn
#

Yeah I get what you mean

crude crater
#

What do I put? Do you know?

slate swan
#

What would be the best way to delete all the messages from a specific user in a channel

crude crater
slate swan
#

that definitely is not the best way

south needle
#

If I wanted to ban someone if they try to change the guild icon how would I go about that?

slate swan
#

!d discord.TextChannel.purge

unkempt canyonBOT
#

await purge(*, limit=100, check=..., before=None, after=None, around=None, oldest_first=None, bulk=True, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Purges a list of messages that meet the criteria given by the predicate `check`. If a `check` is not provided then all messages are deleted without discrimination.

You must have the [`manage_messages`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_messages "discord.Permissions.manage_messages") permission to delete messages even if they are your own. The [`read_message_history`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.read_message_history "discord.Permissions.read_message_history") permission is also needed to retrieve message history.

Changed in version 2.0: The `reason` keyword-only parameter was added.

Examples

Deleting botโ€™s messages...
crude crater
#

Like when they change it it automatically bans them?

south needle
#

yeah like that

crude crater
#

I have no idea brother, that has to do with the audit logs prolly

#

Which I have absolutely no idea how to tamper with

south needle
#

all good

vast gale
crude crater
#

I'm trying to compile a list of the guild ID's that my bot is in

vast gale
vast gale
crude crater
#
 @bot.command()
async def leave(ctx):
    toleave = bot.get_server("id")
    await bot.leave_server(toleave)
#

This is my code, and rigth after "ctx," I need to write whatever "guild ID" is

#
@bot.command()
async def servers(ctx):
        activeservers = bot.guilds
        for guild in activeservers:
            await ctx.send(guild.name)
            print(guild.name)
crude crater
#

This is my code to compile all of the servers, what I need help with is to put the ID's of the servers next to the servers name on the list that my bot makes, and then for the "leave" command I need to be able to put the guild ID after "leave" and have my bot leave that server

south needle
#

can you change the guild icon using guild.edit?

crude crater
#

It only took 2 and a half hours

slate swan
#
@tasks.loop(seconds=5)
async def randommessage():
    channel = client.get_channel(994367892000870421)
    await channel.send("test")

For some reason this doesn't send the word "Test" in that channel every 5 seconds
How can this be fixed?

full lily
#

did you start the task?

slate swan
#

no

slate swan
cloud dawn
#

Yesn't

slate swan
#
Unhandled exception in internal background task 'randommessage'.
Traceback (most recent call last):
  File "C:\Users\rscdo\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\ext\tasks\__init__.py", line 101, in _loop
    await self.coro(*args, **kwargs)
  File "main.py", line 18, in randommessage
    await channel.send("test")
AttributeError: 'NoneType' object has no attribute 'send'

I got this error when the program started

cloud dawn
#

Fetch the channel.

slate swan
#

how can I forbid a specific user to use slash commands via user id? lib: d.py 2.0

cloud dawn
#

You can make a custom check for it but it will be visible.

cloud dawn
slate swan
#

ok lemme fix dat

cloud dawn
slate swan
#

so like await client.fetch_channel(994367892000870421)

slate swan
# cloud dawn You can't

how will it be visible? like when I type / and click on the bot that there is shown: you have no permissions?

crude crater
#
@bot.command()
@commands.is_owner()
async def leave(ctx, guild_id, *, self):
    guild = discord.utils.get(self.bot.guilds, name=guild_id)
    if guild is None:
        await ctx.send("I am not in that server")
        return
    await self.bot.leave_guild(guild)
    await ctx.send(f"I am no longer in {guild.name} ({guild.id})!")

What's wrong with my code?

cloud dawn
crude crater
#

My issue is that when I try to execute the command, I have to also put the "self" when trying to use the command

#

How do I not have that issue?

crude crater
slate swan
#

like dis?

cloud dawn
#

await it

slate swan
#

ok

cloud dawn
slate swan
#

ok lemme try it out

slate swan
slate swan
crude crater
slate swan
#

anyone know where to upload long lines of codes?

cloud dawn
slate swan
#

i need help with something but dont wanna flood chat

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.

slate swan
slate swan
#

i have my token in there but it gives me this error

cloud dawn
crude crater
#

๐Ÿ‘

south needle
#

If a guild has a vanity link how do i get it? is it guild.vanity_url ?

slate swan
cloud dawn
crude crater
#

Preciate it, most people would yell at me and throw a tantrum about "spoonfeeding"

#

You a real one ๐Ÿ˜˜

slate swan
# cloud dawn Did you load the env?

no. im using some youtube tut thing for playing music in just my server but seems as i get error ffmpeg isnt found so im trying another code and idk anyhting about cog

slate swan
cloud dawn
cloud dawn
slate swan
#

thought that was gonna happen when i said that

#

thanks though

cloud dawn
crude crater
#

Thank you lots ๐Ÿ‘

slate swan
slate swan
cloud dawn
slate swan
#

im pretty sure thats the whole purpose of the server, encouraging people to learn python

crude crater
slate swan
#

How could i make this loop work?py @client.command() async def test(ctx): await ctx.send("Test completed! I work!") @tasks.loop(seconds=5) async def randommessage(ctx): print("Test message request recieved!") await ctx.send("Test completed! I work!") randommessage.start()

slate swan
cloud dawn
south needle
#

anyway to retrieve guild vanity?

slate swan
#

sometimes backing away from a discussion is needed to stop it from starting an argument

slate swan
unkempt canyonBOT
slate swan
#

!d discord.Guild.vanity_invite

unkempt canyonBOT
#

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

Returns the guildโ€™s special vanity invite.

The guild must have `VANITY_URL` in [`features`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild.features "discord.Guild.features").

You must have the [`manage_guild`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_guild "discord.Permissions.manage_guild") permission to use this as well.
slate swan
# unkempt canyon

mhm in disnake you can use the use_cacheto convert vanity_url_code to the full invite, thats cool

cloud dawn
slate swan
#

This command gives me this error on file startup:

@client.command()
async def test(ctx):
    await ctx.send("Test completed! I work!")
    @tasks.loop(seconds=5)
    async def randommessage(ctx):
        print("Test message request recieved!")
        await ctx.send("Test completed! I work!")
    randommessage.start()``````Traceback (most recent call last):
  File "nitro.py", line 15, in <module>
    async def test(ctx):
  File "C:\Users\rscdo\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\ext\commands\core.py", line 1263, in decorator
    self.add_command(result)
  File "C:\Users\rscdo\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\ext\commands\core.py", line 1149, in add_command
    raise CommandRegistrationError(command.name)
discord.ext.commands.errors.CommandRegistrationError: The command test is already an existing command or alias.```How can this be fixed
cloud dawn
#

Not have 2 command with the name test

slate swan
#

i want the loop to happen once the command is executed tho

#

and in the channel that its executed

#

so that it can be multiple channels at once

#

hello not related to music at all but ffmpeg was not found but i have done pip install ffmpeg-python

#

and its already installed

cloud dawn
#

That seems pretty related to music lol

unkempt canyonBOT
#

Per Python Discord's Rule 5, we are unable to assist with questions related to youtube-dl, pytube, or other YouTube video downloaders, as their usage violates YouTube's Terms of Service.

For reference, this usage is covered by the following clauses in YouTube's TOS, as of 2021-03-17:

The following restrictions apply to your use of the Service. You are not allowed to:

1. access, reproduce, download, distribute, transmit, broadcast, display, sell, license, alter, modify or otherwise use any part of the Service or any Content except: (a) as specifically permitted by the Service;  (b) with prior written permission from YouTube and, if applicable, the respective rights holders; or (c) as permitted by applicable law;

3. access the Service using any automated means (such as robots, botnets or scrapers) except: (a) in the case of public search engines, in accordance with YouTubeโ€™s robots.txt file; (b) with YouTubeโ€™s prior written permission; or (c) as permitted by applicable law;

9. use the Service to view or listen to Content other than for personal, non-commercial use (for example, you may not publicly screen videos or stream music from the Service)
slate swan
#
@tasks.loop(minutes=5)
async def hello():
    channels = [437680309824258060]  # List of channels
    for ch in channels:
        channel_to_send = client.get_channel(ch)
        await channel_to_send.send("a")```
#

alright alright

slate swan
slate swan
#

hehe i called it

#

oh shi

#

lmao

#

er we go await client.wait_until_ready() fixed it

slate swan
#

you would still need to add a check to that loop even if its in your server

crude crater
#

"Traceback (most recent call last):
File "main.py", line 729, in <module>
async def leave(ctx, guild_i
Traceback (most recent call last):
File "main.py", line 729, in <module>
async def leave(ctx, guild_id: Guild | None = None) -> None:
TypeError: unsupported operand type(s) for |: 'type' and 'NoneType'"

#
@bot.command()
@commands.is_owner()
async def leave(ctx, guild_id: Guild | None = None) -> None:
    if not guild_id:
        return await ctx.send(f"I can't find: {guild_id}")
    
    try:
        await guild.leave()
    except HTTPException:
        return await ctx.send(f"Something went wrong trying to leave {guild_name}")
    await ctx.send(f"I am no longer in {ctx.guild.name} ({ctx.guild.id})!")
#

@cloud dawn Sorry to ping you, but I get this error when I run your code

slate swan
#

panda what is that example

crude crater
#

Nevermind I fixed it lol

#

That example is what was wrong lmao

crisp drift
#

You need py 3.10 to use |

slate swan
#

or a union operator

crisp drift
#

Oh thanks for teaching me kappa

slate swan
#

my pleasure

crisp drift
#

wish u were that good to stay in udevs kekU

slate swan
#

im too good to be in that dead server

crisp drift
#

Whats an Union okimii

slate swan
#

ive only heard about an onion

crude crater
#
@bot.command()
@commands.is_owner()
async def leave(ctx, guild_id):
    if not guild_id:
        return await ctx.send(f"I can't find {ctx.guild_name}")
    
    try:
        await ctx.guild.leave()
    except HTTPException:
        return await ctx.send(f"Something went wrong trying to leave {ctx.guild_name}")
    await ctx.send(f"I am no longer in {ctx.guild.name} ({ctx.guild.id})!")
#

Now my bot just doesn't work

#

Like any commands

#

Nevermind, somehow the leave command made the bot leave the server I was testing it in haha

slate swan
#

await ctx.guild.leave()

#

somehow?

#

that whole command makes no sense๐Ÿ˜ญ

crude crater
#

Well it works kinda

#

So now when I leave, even when I put another guilds ID, it just leaves the discord that I'm using the command in

crisp drift
#

yes

#

because ctx.guild

crude crater
#

OHHHHH

slate swan
#

kai going beast mode

crude crater
#

So what do I do about that?

crisp drift
#

ask coding god okimii

crude crater
#

Okay word

#

Okimii, can you help me?

slate swan
slate swan
crude crater
#

Well I don't care who helps me I just need help lol

crisp drift
#

okimii seems abit mad over me kekU

crisp drift
slate swan
crude crater
#

Or how do I define guild?

#

I don't get it

crisp drift
#

well since its not within a cog just do bot.get_guild(guild_id)

slate swan
#

no code block๐Ÿ˜”

crude crater
#

It still says "Undefined name 'guild_name'"

slate swan
#

because thats not a valid attr afaik

crisp drift
#

cuz of this if not guild_id: return await ctx.send(f"I can't find {ctx.guild_name}")

crude crater
#

So I should get rid of that?

slate swan
crude crater
#

So do I get rid of both of those things?

crisp drift
#

you want to make guild_id optional?

crude crater
#

Wdym?

#

I just want the command to be where I do "!leave [guild ID here]"

#

And then it leaves the server that I put the ID for

crude crater
#

I don't wanna make it optional

#

Sorry I just got what you meant lol

slate swan
#

๐Ÿฟ

crisp drift
#

Then you don't need the first check and in the exception you can change ctx.guild_name to ctx.guild

crude crater
#

And would ctx.guild make the bot leave the server that I did the command in?

slate swan
#

yup

crude crater
#

I don't want that

#

I want the bot to leave the server that I choose

slate swan
#

it can return an instance of a discord.Guild object

crisp drift
#

Guild class

#

not object

crude crater
#

I don't know what that means homie

slate swan
crisp drift
#

You create instance/objects from a class kek

slate swan
#

you make no sense

crude crater
#

Sooooooooooo how do I define the guild name

#

Or how do I define the said guild that I want to leave

slate swan
#

<discord.embeds.Embed object at 0x000001C0CC3DA940>
I get that when i send my embed

embed = discord.Embed(title=":rotating_light: alert", description="**New word incoming!**",color=0xfd00c2)
embed.set_thumbnail(url="--")
``` How can I fix dis
crude crater
slate swan
slate swan
crisp drift
crude crater
slate swan
#

uhm i mean i just did await channel_to_send.send(embed) to send it

crisp drift
#
@bot.command()
@commands.is_owner()
async def leave(ctx, guild_id):
    guild = bot.get_guild(guild_id)
    
    try:
        await guild.leave()
    except HTTPException:
        return await ctx.send(f"Something went wrong trying to leave {ctx.guild}")
    await ctx.send(f"I am no longer in {guild} ({guild.id})!")

@crude crater

slate swan
#

nice one

crisp drift
crisp drift
#

Trying to spit on a code i just copy pasted directly from him kekU

slate swan
crisp drift
#

Okimii come dm u need to learn some more

slate swan
crisp drift
#

No one cares about your flex tries when you dont even know what ure talking about

slate swan
crude crater
#

No error, and the command is on my help list

#

But when I use it how it's intended, NOTHING happens

#

No error, nothing

slate swan
#

its because the guild_id wasnt converted to an int

#

type hint it with an int guild_id: int

crude crater
crude crater
crisp drift
#

in your command params

slate swan
#

in your parameters

crude crater
#

Okay

#

Let me try it

slate swan
#

discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Guild' object has no attribute 'icon_url'

crude crater
#

OH MY GOD OH MY GOD OH MY GOD OH MY GOD

#

It worked!!!!!!

crude crater
#

Thank you so much!!! I literally love you

slate swan
crude crater
#

Mwah!! :*

slate swan
#

i never know what im doing ๐Ÿ˜

#

discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'NoneType' object has no attribute 'url'

FOR REAL

slate swan
slate swan
#

but im sending the cmd in a guild Sob

#

its not the guild

#

oh shit is it bc ion have a server pfp

#

!d discord.Guild.icon

unkempt canyonBOT
slate swan
#

if available.

#

alr ima make a error handler LOL

#

tyty tho SMILE

#

you're welcome :))

#

๐Ÿ˜…

#

im using subfolders bc im weird SMILE

#

oof thats allot of files, maybe you can use cogs and order each command by their category in a cog e.g Moderation only commands

slate swan
slate swan
thick fiber
#

f

#
    @commands.command(aliases=['s'])
    @commands.has_any_role('Dj','dj','DJ')
    async def skip(self, ctx):
        player = self.bot.lavalink.player_manager.get(ctx.guild.id)
        if player.is_playing:
            if ctx.author.guild_permissions.manage_guild or ctx.author.id == player.current.requester or ctx.author.guild_permissions.administrator or ctx.author:
                await ctx.message.add_reaction("โญ๏ธ")
                await player.skip()```

is there a way to check if the author has a role using this 1 liner `if ctx.author.guild_permissions.manage_guild or ctx.author.id == player.current.requester or ctx.author.guild_permissions.administrator or ctx.author:`
#

making a music bot and want the song requester or a dj to be able to skip

slate swan
#

why this happening?

#

out of no where discord.utils and discord.ext.commands are underlined red

south needle
#

'Guild' object has no attribute 'vanity_url_code'

fading marlin
#

you're most likely in pre-2.0 then

slate swan
slate swan
slate swan
#

i have it installed pip

slate swan
slate swan
#

yessir

slate swan
#

and theres this in console

#

nvm got it

crude crater
#
@bot.command()
async def serverinfo(ctx):
    embed = discord.Embed(title=f"{ctx.guild.name} Info", description="Information of this Server", color=discord.Colour.blue())
    embed.add_field(name='๐Ÿ†”Server ID', value=f"{ctx.guild.id}", inline=True)
    embed.add_field(name='๐Ÿ“†Created On', value=ctx.guild.created_at.strftime("%b %d %Y"), inline=True)
    embed.add_field(name='๐Ÿ‘‘Owner', value=f"{ctx.guild.owner.mention}", inline=True)
    embed.add_field(name='๐Ÿ‘ฅMembers', value=f'{ctx.guild.member_count} Members', inline=True)
    embed.add_field(name='๐Ÿ’ฌChannels', value=f'{len(ctx.guild.text_channels)} Text | {len(ctx.guild.voice_channels)} Voice', inline=True)
    embed.add_field(name='๐ŸŒŽRegion', value=f'{ctx.guild.region}', inline=True)
    embed.set_thumbnail(url=ctx.guild.icon_url)    
    embed.set_author(name=f'{ctx.author.name}' icon_url=ctx.message.author.avatar_url

    await ctx.send(embed=embed)
#

It says "icon_url=ctx.message.author.avatar_url" has an invalid syntax

#

How I fix?

crude crater
#

Okay nevermind I just got rid of those 2 last lines

torn sail
#

You forgot a comma

crude crater
#
@bot.command()
async def serverinfo(ctx):
    embed = discord.Embed(title=f"{ctx.guild.name} Info", description="Information of this Server", color=discord.Colour.blue())
    embed.add_field(name='๐Ÿ†”Server ID', value=f"{ctx.guild.id}", inline=True)
    embed.add_field(name='๐Ÿ“†Created On', value=ctx.guild.created_at.strftime("%b %d %Y"), inline=True)
    embed.add_field(name='๐Ÿ‘‘Owner', value=f"{ctx.guild.owner.mention}", inline=True)
    embed.add_field(name='๐Ÿ‘ฅMembers', value=f'{ctx.guild.member_count} Members', inline=True)
    embed.add_field(name='๐Ÿ’ฌChannels', value=f'{len(ctx.guild.text_channels)} Text | {len(ctx.guild.voice_channels)} Voice', inline=True)
    embed.add_field(name='๐ŸŒŽRegion', value=f'{ctx.guild.region}', inline=True)
    embed.set_thumbnail(url=ctx.guild.icon_url)    

    await ctx.send(embed=embed)
#

Now this doesn't work

crude crater
torn sail
#

After the name kwarg

crude crater
#

It's cool if not it's kinda a pain lmao

crude crater
#

No error

#

That's the problem

#

Absolutely NOTHING happens

torn sail
#

What do you want to happen

#

?

crude crater
torn sail
#

Oh ok

#

Well no errors so do you have a error handler?

crude crater
#

I don't think so

torn sail
#

Huh then Iโ€™m not sure why itโ€™s not sending

crude crater
#

๐Ÿคทโ€โ™€๏ธ

slate swan
#

im making a few commands and i get this

paper sluice
#

do embed = discord.Embed()

#

you need to make an instance of it

slate swan
#

ah i didnt see that there

timid beacon
#

maybe you need to edit it too?

colour = discord.Colour.random()
slate swan
#

no no, you just need to actually make an instance over making variables!

slate swan
paper sluice
#

i think they want

discord.Embed(
  color = ...,
  description = ...
)
slate swan
#

nah i didnt mean to put a coma there

paper sluice
#

!e

a = 1,
print(a)
unkempt canyonBOT
#

@paper sluice :white_check_mark: Your eval job has completed with return code 0.

(1,)
slate swan
#

hah

#

blind eye

slate swan
#

but description is still a variable

#

ยฏ_(ใƒ„)_/ยฏ

paper sluice
#

ya, they wanted to pass it directly into the constructor

slate swan
#

anyone know why it just endlessly loads tho?

hushed galleon
slate swan
#

yea i got it to wrok

fluid ore
#

Looks like the ModMail bot isn't working "Your message could not be delivered. This is usually because you don't share a server with the recipient or the recipient is only accepting direct messages from friends. You can see the full list of reasons here:"

#

Obviously we share a server since I'm well typing here, lol

slate swan
#

in this server's settings

#

right click the server icon -> privacy settings -> allow direct messages from server members

#

make sure it's set to on

fluid ore
#

Oh nice, I didn't know you could change that per server, thanks! @slate swan

slate swan
#

ello again im making the command hack like so that dank has and when i do random.choices(names) it shows this

#

jut for these two

slate swan
indigo pilot
#

Is it not possible to do a f string inside a f string??
fStuff f'hello' if x not true else f'lol

#

i get a error when i try

#

thats a horiable example one sec

slate swan
slate swan
unkempt canyonBOT
#

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

Hello World!
slate swan
#

!e

n = "Ash"
s = f"Heck you, {f'{n}'}"
print(s)```
unkempt canyonBOT
#

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

Heck you, Ash
slate swan
#

works

#

hey ash

#

have you ever tried ws?

paper sluice
slate swan
#

like making them

paper sluice
slate swan
slate swan
paper sluice
#

im making copilot write js for me, cuz i will never write that lang myself

indigo pilot
slate swan
indigo pilot
#

trying to a check if theres a role in the db, it shows the role. else it shows "Not Set"

slate swan
indigo pilot
#

but when i try to use a f string for <@{role}>

#

it errors out

slate swan
slate swan
slate swan
slate swan
#

but I dont mind writing pure html and css, I love html ๐Ÿ˜”

paper sluice
slate swan
#

ryuga ew

slate swan
paper sluice
slate swan
#

most people do it

paper sluice
slate swan
#

damn you really hate me๐Ÿ˜”

slate swan
#

ยฏ_(ใƒ„)_/ยฏ

paper sluice
#

everywhere i go, i see ๐Ÿงข

slate swan
paper sluice
slate swan
#

you guys ever used websockets before or what

#

yup

paper sluice
slate swan
#

i used ws with aiohttp now im using wss

slate swan
#

I've never used websockets with python rip

#

no wait only once

#

I feel ryuga

#

โ‰๏ธ

#

I still wonder why the qm is after the em

#

for that emoji*

paper sluice
#

you had one job copilot

slate swan
#

and I hate how i cant shift enter and have to manually change binds in the settings

paper sluice
slate swan
#

I'm already out, you have a github repo for the bot?

paper sluice
#

yea? its just private

slate swan
#

hm

paper sluice
#

idk

#

im dumb

pine marsh
#

ughhh im so lot if anyone can help... ive been stuck for like 6 hours

#
import discord
from time import sleep
import asyncio
import tweepy


discord_token = 'discord_token'
access_token_secret = 'access_token_secret'
access_token = 'access_token'
consumer_secret = 'consumer_secret'
consumer_key = 'consumer_key'

auth=tweepy.OAuthHandler(consumer_key,consumer_secret)
auth.set_access_token(access_token,access_token_secret)
api = tweepy.API(auth)

client=discord.Client()
discord_channel_id='MY_CHANNEL_ID'
@client.event
async def on_ready():
    print('We have logged in as {0.user}'.format(client))
    sleep(0.5)
    print('BOt is Ready!')

@client.event
async def on_message(message):
    if message.author != client.user and str(message.channel.id) ==discord_channel_id :
        api.update_status(status=message.content)


async def main_func():
    await client.start(discord_token)


asyncio.get_event_loop().run_until_complete(main_func())```

For some reason no matter how many times i reset the tokens or api keys for my bot or for twitter api to connect with tweepy it keeps giving me a invalid token passed for line 29 wich would be `api.update_status(status=message.content)` meaning its a twitter api key.... i have reset and verified mutiple times they are correct and also have the correct read & **write** auth on

thanks in advance for any help
#

discord bot but using tweepy to autopost discord messages

#

bot connects, can even get a print in console but when i send a message i get error code for line 29 api.update_status(status=message.content) saying
tweepy.errors.Unauthorized: 401 Unauthorized 89 - Invalid or expired token.

lament mesa
#

maybe invalid token?

pine marsh
#

token is correct 1000000%

hazy oxide
#

try to reset

pine marsh
#

ivve reset it and even tried a second account with elevated access, auth 1.0 ,2.0 ... deleted and created a new bot

#

ive tried everything litterly

pine marsh
lament mesa
lament mesa
pine marsh
#

well the error is wrong lol

lament mesa
#

ยฏ_(ใƒ„)_/ยฏ

pine marsh
#

ive checked the token

#

tokens** mutipkle times

#
discord_token = 'discord_token'
access_token_secret = 'access_token_secret'
access_token = 'access_token'
consumer_secret = 'consumer_secret'
consumer_key = 'consumer_key'```
#

these are the tokens asked for

discord worked as the bot comes online, and responds
api token secret - checked and even reentered
api token - checked and even reentered
consumer secret - checked and even reentered
consumer key - checked and even reentered

anything else you suggest lol

lament mesa
#

did you properly save the script and re-run it?

pine marsh
#

ive deleted the bot, gave it auth 1.0, 2.0 as well as tried it on my acct with elevated api access and still same response

#

yes , ive actually deleted it all and restarted

#

ive been wroking on this for like 6 hours lol

#

never does it take me this long to write and run 40 lines ๐Ÿคฃ

south needle
paper sluice
south needle
slate swan
#

yes

#

looks like emacs

#

but ryuga is using pycharm currently so idk

#

anyone got good command recommendations to add?

paper sluice
#

its pycharm

slate swan
#

ofc

#

pycharm Professionalโ„ข๏ธ

paper sluice
#

nah, i had the same setup in community as well

slate swan
#

^ you can do the same in community as well

#

just use vsc

paper sluice
#

im gonna dual boot my pc with arch then use emacs

lament mesa
#

just use wsl

paper sluice
lament mesa
#

๐Ÿ‘Œ

slate swan
#

how would i fix this?

#

where does request come from?

vale wing
#

You just didn't get to colors, pycharm's color scheme is pretty well customizable

slate swan
#

idk how to do anything with urls

tough lance
slate swan
vale wing
#

Heck

slate swan
#

I wanna cry after what I just wrote

vocal snow
slate swan
paper sluice
slate swan
#

why are you even correcting that code

slate swan
paper sluice
slate swan
#

lmao

paper sluice
slate swan
pine marsh
#

can anyone explain how i could read select outputs from a embed
needing the description and the image... below i have only tried description but any help thanks

@client.event
async def on_message(message):
    if message.author != client.user and str(message.channel.id) ==discord_channel_id :
        embed = message.embeds
        api.update_status(status=embed.description)
        print('done')

I got this that works, but only for messages.. im trying to read a embed and only output description and image

@client.event
async def on_message(message):
    if message.author != client.user and str(message.channel.id) ==discord_channel_id :
        api.update_status(status=message.content)
        print('done')
fleet sand
#

Does anyone here made a bot that also connected with whatsapp?

tough lance
#

Whatsapp has an API as far as I remember

#

You can use that.

tough lance
unkempt canyonBOT
slate swan
#

guys

#

how can i get the content inside an embed

pine marsh
tough lance
#

No

placid skiff
#

first of all we don't even know what that api is, but you don't even need that, once you have the embed object you can modify it and then modify the message where that embed is attached to

pine marsh
placid skiff
#

You can access those with the embed object D_D

spare urchin
#

hey i made a slash command which just simply adds a role to the user using application checks

@client.slash_command(name="vaddrole", description="adds a role to a user")
@application_checks.has_permissions(administrator=True)
async def addrole(interaction: nextcord.Interaction, member: nextcord.Member, role: nextcord.Role):
#

but now i want to send an error message to the user who doesnt have the perms

#

how to do that ??

placid skiff
#

!d discord.ext.commands.Bot.on_command_error

unkempt canyonBOT
#

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

The default command error handler provided by the bot.

By default this logs to the library logger, however it could be overridden to have a different implementation.

This only fires if you do not specify any listeners for command error.

Changed in version 2.0: `context` and `exception` parameters are now positional-only. Instead of writing to `sys.stderr` this now uses the library logger.
spare urchin
#

and it doesnt send the reply

placid skiff
#

what is that application_checks?

spare urchin
#

its there in its docs

#

nextcord docs

placid skiff
#

it doesn't raise missing permission, read the docs again

#

!d nextcord.ext.application_checks.has_permissions

unkempt canyonBOT
#

@nextcord.ext.application_checks.has_permissions(**perms)```
A [`check()`](https://nextcord.readthedocs.io/en/latest/ext/application_checks/index.html#nextcord.ext.application_checks.check "nextcord.ext.application_checks.check") that is added that checks if the member has all of the permissions necessary.

Note that this check operates on the current channel permissions, not the guild wide permissions.

The permissions passed in must be exactly like the properties shown under [`nextcord.Permissions`](https://nextcord.readthedocs.io/en/latest/api.html#nextcord.Permissions "nextcord.Permissions").

This check raises a special exception, [`ApplicationMissingPermissions`](https://nextcord.readthedocs.io/en/latest/ext/application_checks/index.html#nextcord.ext.application_checks.ApplicationMissingPermissions "nextcord.ext.application_checks.ApplicationMissingPermissions") that is inherited from [`ApplicationCheckFailure`](https://nextcord.readthedocs.io/en/latest/api.html#nextcord.ApplicationCheckFailure "nextcord.ApplicationCheckFailure").

If this check is called in a DM context, it will raise an exception, [`ApplicationNoPrivateMessage`](https://nextcord.readthedocs.io/en/latest/ext/application_checks/index.html#nextcord.ext.application_checks.ApplicationNoPrivateMessage "nextcord.ext.application_checks.ApplicationNoPrivateMessage").
spare urchin
maiden fable
#

Yea

#

@commands.has_permissions(kick_members = True)

placid skiff
#

It depends if application commands inherits from commands D_D

#

but why you should rewrite the entire command

#

just change the isinstance D_D

spare urchin
maiden fable
#

command or commands?

spare urchin
#

command ;-;

#

changed

maiden fable
#

Huh show code

paper sluice
spare urchin
#

i will send in dms

placid skiff
#

Bruh literally you had only to change the class in the isinstance method D_D

pine marsh
#

i just caint figure out how to read the embed readout as im sending tweets every time a embed posted.... so im just looking for something like this i suppose

api.update_status(status=discord.Message.embeds(description, url_title))
gaunt mortar
#

Hello, does someone know why when I try to set an image in an embed message it looks like this ?

@app_commands.command(name="image", description="Send a random image")
    async def image(self, interaction):
        link = SCREENSHOT_URL + ''.join(random.choice(string.ascii_lowercase + string.digits) for i in range(6))
        embed = discord.Embed(color=0xda8607)
        embed.set_image(url=link)
        await interaction.response.send_message(embed=embed)

When I'm using the link there is an image, but it is not displayed.

gaunt mortar
robust fulcrum
#

Hi ash

slate swan
#

hi

slate swan
robust fulcrum
#

The get_prefix

slate swan
#

nice

#

what's it

robust fulcrum
slate swan
#

nice

robust fulcrum
#

Nice nice nice nice

minor sun
#

import os

from discord.ext import commands

DISCORD_BOT_TOKEN = os.getenv("DISCORD_BOT_TOKEN")

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

for filename in os.listdir("./cogs"):
if filename.endswith(".py") and filename != "init.py":
bot.load_extension(f'cogs.{filename[:-3]}')

print(DISCORD_BOT_TOKEN)

#

does someone by any chance know why pycharm doesnt read my bots token in the .env file?

#

thought i did it right apparently not since the print shows: none

robust fulcrum
#

๐Ÿง

slate swan
# robust fulcrum What you mean?

just create a function that takes bot and messages parameters and make the function return a string/iterable of strings, and set the command_prefix=prefix_func_name

robust fulcrum
#

I wanted to ask that whats use of bot in it?

slate swan
#

it represents a Bot obj

#

just have it as a parameter, it's not necessary to be used

robust fulcrum
#

Oh k

paper sluice
#
def prefix(_bot: commands.Bot, message: discord.Message) -> ...:
    ...
#

remove the _ if you will use it

#

which you probably will to access the db connection

robust fulcrum
#

How can we get message guild I'd?

lament mesa
paper sluice
slate swan
#
from typing import Any

class MyBot(commands.Bot):
  def __init__(self) -> None:
    super().__init__(command_prefix=self.get_pre, intents=intents)
    self.prefixes = {}  

  def get_pre(self, bot: commands.Bot, message: discord.Message) -> Any:
    return self.prefixes.get(message.guild.id, "!")

something like that

unkempt canyonBOT
minor sun
slate swan
#

you need to load the env too

robust fulcrum
#

How to select guild I'd and get prefix?

slate swan
#

dotenv.load_dotenv()

lament mesa
shrewd apex
#

rip

lament mesa
#

put it at the start

paper sluice
shrewd apex
#

u have to provide path for the .env file as well

minor sun
#

omg ye i just saw in the docs u guys are amazing thanks

shrewd apex
robust fulcrum
slate swan
#

I don't even need this library most of the times,my .envs work fine without loading manually

minor sun
paper sluice
slate swan
paper sluice
robust fulcrum
robust fulcrum
paper sluice
lament mesa
slate swan
# robust fulcrum I asking how to

that depends on like 3-4 things
what database you are using
whats your data format structure
and the data type you use for keys/fields

paper sluice
# robust fulcrum I asking how to
cur.execute("SELECT prefix FROM table WHERE id=?", {guild.id})
prefix = cur.fetchone()

this should work, i haven't worked with sqlite for a long long time

robust fulcrum
#

And guild _id is int and prefix is str

slate swan
#

and whats your table structure?

#

then just use what ryuga sent

robust fulcrum
paper sluice
#

that was a vague solution, you need to create a table with id an prefix columns first

robust fulcrum
paper sluice
#

once you create the table, you store the id and prefix then you can get it using that

paper sluice
slate swan
#

don't create so many connections

paper sluice
#

ya connect in the setup_hook itself

robust fulcrum
#

And will it be prefix=get_prefix or prefix=get_prefix()

slate swan
#

you're literally making a new connection everytime someone sends a message and not even closing iy

slate swan
slate swan
#

but not in the get_prefix

paper sluice
#

or do this

async def main():
  async with bot:
      async with aiosqlite.connect(...) as connection:
          bot.connection = connection
          await bot.start()
#

and then use bot.connection

robust fulcrum
#
import aiosqlite
import discord
from discord.ext import commands
import asyncio

def get_prefix(Bot, message):
    connect = await aiosqlite.connect('prefixes.db')
    cursor = await connect.cursor()
    id = message.guild.id
    await cursor.execute('SELECT prefix FROM prefixes where guild_id=?',{id})
    prefix = await cursor.fetchone()
    if prefix:
        return prefix
    else:
        return '~'
    await connect.commit()
    await connect.close()

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

async def connect():
    bot.connect = await aiosqlite.connect('prefixes.db')
    cursor = await bot.connect.cursor()
    await cursor.execute('CREATE TABLE IF NOT EXISTS prefixes(guild_id INTEGER,prefix TEXT)')
    await bot.connect.commit()
    await bot.connect.close()

bot.setup_hook = connect

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

Is it fine?

paper sluice
#

why don't people use cm where it can be used ๐Ÿ˜”

paper sluice
#

contextmanager

robust fulcrum
#

Anyway it's fine for my level

paper sluice
#

there is nothing complicated about it

#

!e

class Foo:
    def __enter__(self, *a): # i dont remember what args they took
      print('enter')
    def __exit__(self, *a):
      print('exit')

with Foo() as f:
    print('inside')

with Foo() as f:
    raise Exception()
unkempt canyonBOT
#

@paper sluice :x: Your eval job has completed with return code 1.

001 | enter
002 | inside
003 | exit
004 | enter
005 | exit
006 | Traceback (most recent call last):
007 |   File "<string>", line 11, in <module>
008 | Exception
slate swan
paper sluice
#

๐Ÿ‘€ pithink