#discord-bots

1 messages ยท Page 1019 of 1

brave forge
#

Command raised an exception: TypeError: dump() missing 1 required positional argument: 'fp'

supple thorn
#

But still can fuck your shit if you don't know how to fix it

#

Yes

#

Also you should use this instead

#

!d discord.ext.commands.Bot.listener

brave forge
#

it doesn't work. After this stuff, the bot no longer responds to commands!!!

velvet compass
supple thorn
#

Hi brad

brave forge
glad thicket
#

for now I am going to use discord-slash can you tell me what's worng with my code

supple thorn
velvet compass
supple thorn
#

And other stuff

velvet compass
#

sorry, caps

slate swan
#

the library is outdated

brave forge
supple thorn
slate swan
supple thorn
slate swan
#

!pip discord-py-interactions

unkempt canyonBOT
swift crane
brave forge
supple thorn
supple thorn
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.

supple thorn
#

If you don't already

swift crane
supple thorn
swift crane
#

i know and it is on

brave forge
supple thorn
#

Oh why didn't i see that ctx

#

It's supposed to be msg.delete()

swift crane
supple thorn
#

There is no ctx

#

It's msg

swift crane
#

so...

supple thorn
#

No

#

on_message doesn't take ctx

#

It's just message

#

So just use that message object

#

And delete the message

swift crane
velvet compass
# brave forge WHAT !?
your_word = ... # returned from your command
with open("your_json_file.json", "a+") as f:
    json_data = json.dumps(your_word)
    f.write(json_data)

This could be one solution to your problem. Although writing multiple times to a json file can break it pretty easily.

supple thorn
#

Yes

#

I have to stop being here 12 hours a day

swift crane
supple thorn
#

I should be in the esoteric channel

swift crane
#

?

swift crane
#

i love people like you

#

you helped me

velvet compass
midnight gorge
#

use 2.0.

#

also remove third party lib they're not supported for 2.0

brave forge
swift crane
supple thorn
#

The esoteric channel reminds me of the time i tried brainfuck

velvet compass
swift crane
supple thorn
#

Check if the message content is inside the list

velvet compass
#

So you have to take care when reading and writing

supple thorn
#

Not if the list is inside the message content

quaint epoch
#

!pypi better_profanity

unkempt canyonBOT
brave forge
swift crane
#

?

supple thorn
#

Yes

quaint epoch
supple thorn
brave forge
supple thorn
#

Oh wait... there's a lib for that

#

!pypi bitches

unkempt canyonBOT
quaint epoch
velvet compass
quaint epoch
#

god that was sus

velvet compass
#

Oh nice, then you can create a "bad words" entry or something like that, and append your bad words to that column

loud junco
#

๐Ÿ’€

brave forge
loud junco
#

btw how do i make the vote detector in top.gg

quaint epoch
#

i haven't used it personally

swift crane
loud junco
slate swan
#
class Ticket(discord.ui.View):
    def __init__(self):
        super().__init__(timeout=None)
    @discord.ui.button(label='๐Ÿ“ฉOpen ticket', style=discord.ButtonStyle.blurple, custom_id = 'open-ticket')
    async def button_callback(self, button, interaction):
        guild = interaction.guild```
AttributeError: 'Button' object has no attribute 'guild'
velvet compass
slate swan
#

Please help guys, idk how the interaction is a button

quaint epoch
swift crane
loud junco
supple thorn
unkempt canyonBOT
supple thorn
paper sluice
#

๐Ÿ˜

swift crane
#

my god

#

thanks

visual island
brave forge
supple thorn
#

I wish that man the best

paper sluice
#

๐Ÿ‘€ imma have a look ig

velvet compass
quaint epoch
#

im gonna try to make a package that filters swears

slate swan
loud junco
#

anyone knows how to do top.gg vote detector?

quaint epoch
loud junco
#

but only one person answer me

supple thorn
quaint epoch
loud junco
#

i tried and have no idea

supple thorn
loud junco
#

๐Ÿ’€

supple thorn
#

We can fix that

loud junco
#

ok

#

maybe i try framing it

supple thorn
loud junco
#

i think so

supple thorn
#

!pypi topggpy

unkempt canyonBOT
supple thorn
loud junco
#

i legit send that :/

glad thicket
#

hey how do you create a slash command in discord-py-interactions

paper sluice
loud junco
#

i need webhook for that right?

brave forge
supple thorn
paper sluice
loud junco
supple thorn
paper sluice
#

hello brad

velvet compass
supple thorn
#

I'm replying to it so that you get pinged

#

I did the this to show you the api wrapper

brave forge
supple thorn
paper sluice
#

*more reactions for me to click on *

velvet compass
slate swan
#
transcript = await chat_exporter.export(channel, set_timezone='CET')
        transcript_file = discord.File(io.BytesIO(transcript.encode()),filename=f"{channel.name}.html")```
AttributeError: 'NoneType' object has no attribute 'encode'
Anyone knows why this doesn't work?
paper sluice
# slate swan

ur try-except is outside the function, indent it properly

cloud dawn
supple thorn
cloud dawn
#

!with

unkempt canyonBOT
#

The with keyword triggers a context manager. Context managers automatically set up and take down data connections, or any other kind of object that implements the magic methods __enter__ and __exit__.

with open("test.txt", "r") as file:
    do_things(file)

The above code automatically closes file when the with block exits, so you never have to manually do a file.close(). Most connection types, including file readers and database connections, support this.

For more information, read the official docs, watch Corey Schafer's context manager video, or see PEP 343.

supple thorn
#

What

velvet compass
slate swan
#

oh wait

paper sluice
velvet compass
slate swan
#

hmm

supple thorn
#

Why limit out power

cloud dawn
slate swan
velvet compass
#

#python-discussion and #discord-bots have the reactions disabled because people spamed / abused them (in the past and there have been decisions made on it before my time). And we can't effectively moderate reactions

paper sluice
# slate swan

ur try and except block must be at the same indent level

try: 
  ...
except:
 ...

valid ^^

try: 
  ...
  except:
    ...

invalid ^^

paper sluice
#

yea

slate swan
#

imagine opening a json file every message

paper sluice
#

people with special roles

supple thorn
cloud dawn
velvet compass
supple thorn
paper sluice
slate swan
brave forge
supple thorn
cloud dawn
supple thorn
#

Beer with an accent?

cloud dawn
paper sluice
supple thorn
cloud dawn
supple thorn
cloud dawn
velvet compass
#

They are clicking on your profile (and your spotify is linked)

paper sluice
cloud dawn
paper sluice
#

lil ot here and there is fine

#

this is a python server not school

cloud dawn
#

But it was so random tough lol

paper sluice
#

that i agree

velvet compass
manic path
#
    embed.set_author(XYZ["name"])
TypeError: Embed.set_author() takes 1 positional argument but 2 were given

XYZ['name'] is literally a string
print(XYZ['name'] = XYZ Information

cloud dawn
unkempt canyonBOT
#

set_author(*, name, url=None, icon_url=None)```
Sets the author for the embed content.

This function returns the class instance to allow for fluent-style
chaining.
manic path
cloud dawn
#

(*, name, url=None, icon_url=None)

#

* < indicating that everything is a keyword argument. And that name here is a required kwarg.

#

url and icon_url are optional.

manic path
#

right

cloud dawn
manic path
#

ye

boreal ravine
slate swan
#

how do i add custom emoji to a message?

slate swan
slate swan
#

yea

#

Not "react"

#

But it's the same pattern

#

example:

slate swan
#

Add \ before your emoji, send it and copy paste that

#

<:emoji_name:emoji_id>
^^
you can either get this by putting a backslash before the emoji or put them manually

#

If you can't send the emoji you can get its id and name

#

</:kiff:970673345643307088>

#

Without /

#

i know

#

second

#

Seems like it's not a valid emoji ID

slate swan
#

How to add this thing on my script anyone?

#

Very original at copying a bot ๐Ÿ‘€

#

Web one

slate swan
#

How did you tried to get the ID?

#

Like this

slate swan
slate swan
#

See the screenshot

#

Not really directly related to bots; more like Python and Replit, which is bad

#
from flask import Flask

from threading import Thread



app = Flask('ok')



@app.route('/')

def home():

    return "I'm alive"



def run():

  app.run(host='0.0.0.0',port=8080)



def keep_alive():  

    t = Thread(target=run)

    t.start()
#

I already add this

#

Again, not directly related to discord bots.

#

So?

#

As you can see it's flask

#

Yes?

#

So? So this is a topical channel.

slate swan
#

Ohh k

#

i`m send emoji

#

and

#

That doesn't give the ID

#

That gives, most likely, the message ID

#

oh

#

๐Ÿ˜ณ

#

how to get ID emoji?

#

Hmm well, without Nitro it's complicated to explain

#

ok

#

Ctrl+Shift+I -> Click on the icon at the top right here

#

I will try myself

#

Then hover with the mouse on the emoji

#

Click on it

#

You get to a thing like this

#

And data-id is your emoji ID

#

970602565244973086

#

More accurate yep

#

wait

slate swan
#

YES, it work

#

thx so much

slate swan
#

Especially animated ones

slate swan
#

For static you can just use \:emoji:

slate swan
regal pulsar
#

my friend used the same template

#

why would you want your serverinfo command to mention every bot in the server ๐Ÿ’€

slate swan
#

Not so pog

supple thorn
#

I wonder if you can torture someone with python

#

Imagining the fbi using python to get intel from the enemy

quaint epoch
slate swan
#

I want bot status like this anyone?

quaint epoch
#

you can't sorry

amber bloom
#

Hello, how to detect if a member have nitro booster please?

slate swan
#

you can't set the bot status to mobile

quaint epoch
unkempt canyonBOT
#

class disnake.Member```
Represents a Discord member to a [`Guild`](https://docs.disnake.dev/en/latest/api.html#disnake.Guild "disnake.Guild").

This implements a lot of the functionality of [`User`](https://docs.disnake.dev/en/latest/api.html#disnake.User "disnake.User").

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

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

hash(x) Returns the memberโ€™s hash.

str(x) Returns the memberโ€™s name with the discriminator.
quaint epoch
#

there should something about premium there

slate swan
amber bloom
slate swan
#

it's possible to set a bot's status to online on mobile

quaint epoch
#

eh

#

!d disnake.User.public_flags

unkempt canyonBOT
slate swan
#

in discord.js for example you can override the websocket connection parameters

quaint epoch
#

aha @amber bloom there you go

slate swan
#
const client = new Discord.Client({ ws: { properties: { $browser: "Discord iOS" }} });```
#

What's that?

pseudo portal
#

can someone help me here, usin pycord, tryina make it so my bot lists all servers its on with invites on run

slate swan
#

Ohh k

quaint epoch
#

and i helped you?

pseudo portal
#

been tryin and tryin lol

amber bloom
quaint epoch
#
for guild in bot.guilds:
  print(f'Invites in {guild}', str(await guild.invites()))```
#

but isn't that kinda against tos

#

because in this way, you can find your way in private servers

pseudo portal
#

yo @quaint epoch btw howd u get that date in your bio to be hoverabl with info

pseudo portal
quaint epoch
#

!d disnake.utils.format_dt

unkempt canyonBOT
#

disnake.utils.format_dt(dt, /, style='f')```
A helper function to format a [`datetime.datetime`](https://docs.python.org/3/library/datetime.html#datetime.datetime "(in Python v3.10)"), [`int`](https://docs.python.org/3/library/functions.html#int "(in Python v3.10)") or [`float`](https://docs.python.org/3/library/functions.html#float "(in Python v3.10)") for presentation within Discord.

This allows for a locale-independent way of presenting data using Discord specific Markdown...
quaint epoch
#

i usually use a datetime object

#

<t:19129393>

#

<t:19129393>

#

it returns a string like that

pseudo portal
quaint epoch
#

oh in your BIO

pseudo portal
#

Ooh Iโ€™mma have to try that when get back on pc ๐Ÿ˜‰ Ty bro

quaint epoch
#

i don't think you can do that

pseudo portal
#

Hmm

#

Wdym?

quaint epoch
#

you can't mention ppl in your bios

slate swan
pseudo portal
pseudo portal
slate swan
#

Hmm

paper sluice
slate swan
#

๐Ÿ˜ถ

slate swan
paper sluice
#

install keep_alive

#

and use os.listdir or pathlib.Path to load cogs instead of importing

slate swan
#

Hmm m

#

i need context on why you would need keep_alive?

#

isn't it obvious

paper sluice
slate swan
#

botching to keep a container on

placid skiff
#

Ops wrong ping

slate swan
sick birch
slate swan
#

replit yeah

#

ever heard of context?

#

thank you

sick birch
#

which is very bad but it works I suppose

slate swan
#

yeah

atomic wolf
#

def __init__(self):

#

I'm confused about this expression. Could anyone explain it to me?

slate swan
#

time woyls be a module a d .respond isnt a method and dont use time.sleep it would block your whole bot and not the coro so use asyncio.sleep

#

!d asyncio.sleep

unkempt canyonBOT
#

coroutine asyncio.sleep(delay, result=None)```
Block for *delay* seconds.

If *result* is provided, it is returned to the caller when the coroutine completes.

`sleep()` always suspends the current task, allowing other tasks to run.

Setting the delay to 0 provides an optimized path to allow other tasks to run. This can be used by long-running functions to avoid blocking the event loop for the full duration of the function call.

Deprecated since version 3.8, removed in version 3.10: The `loop` parameter. This function has been implicitly getting the current running loop since 3.7. See [Whatโ€™s New in 3.10โ€™s Removed section](https://docs.python.org/3/whatsnew/3.10.html#whatsnew310-removed) for more information.

Example of coroutine displaying the current date every second for 5 seconds:
quick gust
#

!d discord.Invite.code

unkempt canyonBOT
quick gust
#

ure printing the Invite objects, what else did u expect

dull terrace
#

anyone tried out integrations for their bots yet

#

seems to not limit it to certain channels froggy_chill

pseudo portal
#

but otherwise it works fine for me with normal members

dull terrace
#

7739monkathink i've gotta use another account to test it

#

makes sense, i didn't think of that

pseudo portal
#

yessirr xD

#

gl! ๐Ÿ˜‰

supple thorn
#

Ask somewhere else since it isn't related to discors bots

regal pulsar
#

for eg

slate swan
regal pulsar
#
class Test:

  instances = 0

    def __init__(self):
        Test.instances += 1
test1 = Test()
test2 = Test()
print(Test.instances)
#

lmao @slate swan

slate swan
regal pulsar
wanton veldt
#
    config = {}
    with open("stats.json", "r") as f:
        config = json.loads(f.read())

    async def statusTask():
        while True:
            for status in config["statuses"]:
                if status["type"] == "game":
                    await client.change_presence(activity=discord.Game(name=status["name"], start=datetime.datetime.now()-datetime.timedelta(status["duration"]), end=datetime.datetime.now()))
                if status["type"] == "stream":
                    await client.change_presence(activity=discord.Streaming(name=status["name"], platform="YouTube", url=status["url"]))
                if status["type"] == "competing":
                    await client.change_presence(activity=discord.Activity(name=status["name"], type=5,))
                if status["type"] == "watching":
                    await client.change_presence(activity=discord.Activity(name=status["name"], type=3,))
                if status["type"] == "listening":
                    await client.change_presence(activity=discord.Activity(name=status["name"], type=2))
                await asyncio.sleep(status["delay"])

    @client.event
    async def on_ready():
        print(f"{client.user.name} has connected to Discord.")
        client.loop.create_task(statusTask())```
can someone help me?
#

the error is in the photo

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
#

format it first

wanton veldt
paper sluice
wanton veldt
#

and its possible to make a server counter in stats using json?

paper sluice
#

calculate it before and put that in the json

wanton veldt
#

how exactly

slate swan
#

the member is returning None

paper sluice
regal pulsar
#

member is none

#

which means either _id is None

#

or there isnt any user with that id

slate swan
#

Iโ€™m getting an error:
discord.ext.commands.errors.CommandInvokeError: a Command raised an exception: name โ€˜discordโ€™ is not defined

slate swan
#

I have it

#

Wait

#

Nvm

#

I had pasted a code in another file without import discord

#

Sorry for inconvenience

bleak karma
#

how can i make self.bot work in button views

slate swan
#

@slate swan How do I typehint a Member in the option decorator of a slash command?
for example

@command
@option(name="member", required=False)

and I wanna have the member as a Member object ๐Ÿ˜”

slate swan
#

and it will popup with a list of members in the server as an autocomplete too :3

slate swan
#

lmao

flint isle
#
Developed by: David Powell
Starting Bot
Connecting to Discord API.
Please Wait
[VERSION]{}
Loading Developer Features cog
[โœ“][Developer Features Cog] Loading Complete
Traceback (most recent call last):
  File "/data/user/0/ru.iiec.pydroid3/files/accomp_files/iiec_run/iiec_run.py", line 31, in <module>
    start(fakepyfile,mainpyfile)
  File "/data/user/0/ru.iiec.pydroid3/files/accomp_files/iiec_run/iiec_run.py", line 30, in start
    exec(open(mainpyfile).read(),  __main__.__dict__)
  File "<string>", line 60, in <module>
NameError: name 'mid' is not defined

[Program finished]

error ^
code:

@bot.command(name='msg')
async def msg(ctx,  optional_arg: mid = None):
    message = await ctx.fetch_message(id=mid)```
flint isle
slate swan
#

i completed my giv cmd buttons

#

okay

#

wanna see?

slate swan
#

โ˜น๏ธ

atomic wolf
#

Is CustomClient a thing like a keyword?

slate swan
atomic wolf
#

class CustomClient(discord.Client): def __init__(self): super(CustomClient, self).__init__() with open("allykeys.json") as jfile: data = json.load(jfile) self.oauthsecret = data["oauthsecret"] self.oauthtoken = data["oauthtoken"] self.consumerkey = data["consumerkey"] self.api = AllyAPI(self.oauthsecret, self.oauthtoken, self.consumerkey, response_format="json") def exit(self): exit(0)

slate swan
#

๐Ÿ‘€

bleak karma
#

is it possible to make self.bot work in button views (repost)

atomic wolf
#

I guess I'm confused on the super(CustomClioent, self).__init__

#

just its purpose

slate swan
#

ok

slate swan
atomic wolf
#

It's like a discord stock info bot code example

#

I keep forgetting to think about indents.

bleak karma
slate swan
#

huh?

atomic wolf
#

I'm used to C++ or something.

#

curly braces

slate swan
bleak karma
slate swan
#

then

#

pass

#
class giveaway(disnake.ui.View):
    def __init__(self , bot: commands.Bot):
        self.bot = bot
slate swan
# bleak karma yup

pass the bot into the init function of the class, then pass in the actual bot when you subclass the view class

class MyUwUView(View):
  def __init__(self, bot: Bot):
    self.bot = bot

@command
await send(view=MyUwUView(bot_instance))
slate swan
#

:<

bleak karma
#

oh i didnt see your response im so sorry

slate swan
slate swan
slate swan
slate swan
#

same goes with disnake, I'm against the forks now too

slate swan
#

then ?

#

nextcord?

#

dont

slate swan
#

yes

#

but what do u use now

slate swan
#

๐Ÿ˜”

#

why?

slate swan
atomic wolf
#

class CustomClient(discord.Client): def __init__(self): super(CustomClient, self).__init__() with open("allykeys.json") as jfile: data = json.load(jfile) self.oauthsecret = data["oauthsecret"] self.oauthtoken = data["oauthtoken"] self.consumerkey = data["consumerkey"] self.api = AllyAPI(self.oauthsecret, self.oauthtoken, self.consumerkey, response_format="json") def exit(self): exit(0)

slate swan
#

idk much about hikari i mean why u choose it, reason

atomic wolf
#

i was wondering if def __init__(self): is a subclass of CustomClient

heady sluice
#

Ashley's used to hikari being bullied so she just answers why not

atomic wolf
#

and then hence the use of the super keyword

slate swan
#

its better than dpy at least

bleak karma
#

idk if i did it right but

class verykoolview(discord.ui.View):
    def __init__(self, bot:commands.Bot, *, timeout=None):
        self.bot = bot
        super().__init__(timeout=timeout)

and i got an error

Traceback (most recent call last):
  File "/home/runner/pity/venv/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 1325, in invoke
    await ctx.command.invoke(ctx)
  File "/home/runner/pity/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 948, in invoke
    await injected(*ctx.args, **ctx.kwargs)  # type: ignore
  File "/home/runner/pity/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 209, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: __init__() missing 1 required positional argument: 'bot'
slate swan
#

verykoolview(bot instance)

slate swan
bleak karma
#

OH

heady sluice
#

bot.add_cog(CogObject(bot))

#

(await maybe)

slate swan
#

def setup(bot: commands.Bot):
bot.add_cog(noob(bot))

heady sluice
#

load_extension only calls setup

slate swan
#

i posted half code

bleak karma
#

it worked tysm guys

marsh thorn
#
import time, webbrowser, pyttsx3, discord
from discord import user, message
from discord.ext.commands import bot
TOKEN = 'SDF154s5df415D444'
client = discord.Client()

@client.event
async def on_ready():
    print('botloggedin as {0.user}'.format(client))

@client.event
async def on_message(message):
 username = str(message.author).split('#')[0]
 user_message = str(message.content)
 channel = str(message.channel.name)
 print('botloggedin as {0.user}'.format(client))
 if message.channel.name == 'general':
  if user_message.lower() == '!isrunning':
   await message.channel.send("The bot is currently running")
 return
 client.run(TOKEN)

Why doesnt this work?

#

no errors btw

slate swan
#

Missing Message content intent

#

!intents

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
#

why intents dont raise error

#

Because it doesn't make sense

#

..

#

You just don't get the message content in that case

#

And for others you don't get the even dispatched

stone beacon
#

Ik the api does return an error it's just some of the forks

slate swan
#

API doesn't return an error at all.

stone beacon
#

I'm 80% sure I saw an intent error already

slate swan
#

It doesn't dispatch the event or doesn't give the content field to the message

stone beacon
#

When Intents first dropped

slate swan
#

There is an error when you enable a privileged intent with code and you didn't enable it in the developer portal, yes.

stone beacon
#

Them that's what I probably did

slate swan
#

But not an error because you're trying to access .content or catch the dispatched events, doesn't make any sense

stone beacon
#

CUz when they came and caused an uproar with the new intents I just enabled them locally and saw the error that I had to enable em

slate swan
#

Yeah that's most likely what you've got

atomic wolf
#

snoggy, what a name, haha

#

so __init__ is a constructor because just because?

stone beacon
#

Indeed, I've had this name set here since I joined the server back in 2020

heavy folio
#

__init__ is to initialise the obj's class
if you subclass, by calling super().__init__(*args, **kwargs) you are instantiating the object from the original inheritance

atomic wolf
#

so it's a way of making an object have the fields of the higher class despite being originally defined on a lower one?

unkempt canyonBOT
#

Hey @marsh thorn! I noticed you posted a seemingly valid Discord API token in your message and have removed your message. This means that your token has been compromised. Please change your token immediately at: https://discordapp.com/developers/applications/me

Feel free to re-post it with the token removed. If you believe this was a mistake, please let us know!

marsh thorn
#

it didnt have a real token lol

stone beacon
#

Just leave the token field blank

marsh thorn
#
import time, webbrowser, pyttsx3, discord
from discord import user, message, Intents
TOKEN = ''
client = discord.Client()

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

@client.event
async def on_ready():
    print('botloggedin as {0.user}'.format(client))

@client.event
async def on_message(message):
 username = str(message.author).split('#')[0]
 user_message = str(message.content)
 channel = str(message.channel.name)
 print('botloggedin as {0.user}'.format(client))
 if message.channel.name == 'general':
  if user_message.lower() == '!isrunning':
   await message.channel.send("The Bot is currently running")
 return
 client.run(TOKEN)

Why doesnt this work?

marsh thorn
heavy folio
#

i can see that you are trying to get message.author's name from ```py
username = str(message.author).split('#')[0]

and no need to cast message.content (already a string) to a string, likewise for message.channel.name
marsh thorn
marsh thorn
heavy folio
heavy folio
heavy folio
unkempt canyonBOT
#

property name```
Equivalent to [`User.name`](https://discordpy.readthedocs.io/en/master/api.html#discord.User.name "discord.User.name")
marsh thorn
slate swan
heavy folio
#

question mark tells me otherwise

slate swan
#

..

slate swan
marsh thorn
slate swan
#

There are a few things you're missing

  1. Actually use the variable intents, right now you're doing nothing with it
  2. Use Bot and not Client, you need to make proper imports which are in the bot's message
marsh thorn
# slate swan There are a few things you're missing 1. Actually use the variable `intents`, ri...
import time, webbrowser, pyttsx3, discord
from discord import user, message, Intents
from discord.ext import commands
TOKEN = ''
client = discord.Client()
bot = commands.Bot(command_prefix="!", intents=Intents)

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

@bot.event
async def on_ready():
    print('botloggedin as {0.user}'.format(client))

@client.event
async def on_message(message):
 username = str(message.author).split('#')[0]
 user_message = str(message.content)
 channel = str(message.channel.name)
 print('botloggedin as {0.user}'.format(client))
 if message.channel.name == 'general':
  if user_message.lower() == '!isrunning':
   await message.channel.send("The Bot is currently running")
 return
 client.run(TOKEN)

like this?

slate swan
#

No

#

Stop using Client

#

And this shows your bot will actually never start

#

It's indented wrongly

marsh thorn
#

oh alr so all clients should be bot

marsh thorn
slate swan
#

Correct

#
Ignoring exception in view <reqs2 timeout=30 children=2> for item <Button style=<ButtonStyle.success: 3> url=None disabled=False label='Invites' emoji=None row=None>:
Traceback (most recent call last):
  File "C:\Users\hp\AppData\Local\Programs\Python\Python38\lib\site-packages\disnake\ui\view.py", line 370, in _scheduled_task
    await item.callback(interaction)
  File "c:\Users\hp\Desktop\bot\giveaway.py", line 343, in but11
    await interaction.response.send_modal(modal=MyModal(self.bot,"Invites Required"))
  File "c:\Users\hp\Desktop\bot\giveaway.py", line 271, in __init__
    super().__init__(
  File "C:\Users\hp\AppData\Local\Programs\Python\Python38\lib\site-packages\disnake\ui\modal.py", line 81, in __init__
    raise ValueError("Maximum number of components exceeded.")
ValueError: Maximum number of components exceeded.
``` hm?
slate swan
#
def x():
  yes()
  something()

def x():
  yes()
something()

This is not the same

#

You have the version above, it should be the version below

marsh thorn
#

oh i see

#

the bot is in the function

velvet haven
#
@commands.command(name="hot",help="Sends hot posts from reddit")
async def hot(self,ctx,subreddit:str):
      submissions = self.reddit.subreddit(subreddit).hot()

      post_to_pick = random.randint(1, 10)
      for i in range(0, post_to_pick):
        submission = next(x for x in submissions if not x.stickied)
      await ctx.send(submission.url)```
coroutine function has no attribute hot
regal pulsar
# marsh thorn ```py import time, webbrowser, pyttsx3, discord from discord import user, messag...
import time, webbrowser, pyttsx3, discord
from discord import user, message, Intents
from discord.ext import commands
TOKEN = ''
client = discord.Client()
bot = commands.Bot(command_prefix="!", intents=Intents)

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

@bot.event
async def on_ready():
    print(f'Logged in as {bot.user}')

@bot.event
async def on_message(message):
 username = str(message.author.name)
 user_message = str(message.content)
 channel = str(message.channel.name)
 print('botloggedin as {0.user}'.format(client))
 if message.channel.name == 'general':
  if user_message.lower() == '!isrunning':
   await message.channel.send("The Bot is currently running")

 bot.run(TOKEN)
slate swan
#

Maximum number of components exceeded.

regal pulsar
#

kinda like

slate swan
#

Still running the bot inside the function, which is not what you want

regal pulsar
#
embed = disnake.Embed()
embed.add_field()
embed.add_field()
embed.add_field()
embed.add_field()
embed.add_field()
#

something like that

slate swan
#

Embeds are not modals

#

Modal*

regal pulsar
#

i know

slate swan
#

Fields are not components

regal pulsar
#

its an example...

slate swan
#

Lol

#

You're just adding too many components, for example fields to write in

regal pulsar
#

yeah

slate swan
#

How much maximum can I add

regal pulsar
#

oh i edited it on discord

#

didnt see the indent

marsh thorn
#
import time, webbrowser, pyttsx3, discord
from discord import user, message, Intents
from discord.ext import commands
TOKEN = ''
bot = commands.Bot(command_prefix="!", intents=Intents)

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

@bot.event
async def on_ready():
    print(f'Logged in as {bot.user}')

@bot.event
async def on_message(message):
 username = str(message.author.name)
 user_message = str(message.content)
 channel = str(message.channel.name)
 print('botloggedin as {0.user}'.format(bot))
 if message.channel.name == 'general':
  if user_message.lower() == '!isrunning':
   await message.channel.send("The Bot is currently running")

bot.run(TOKEN)

is this correct?

slate swan
#

Try it

regal pulsar
#
import time, webbrowser, pyttsx3, discord
from discord import user, message, Intents
from discord.ext import commands

TOKEN = ""
client = discord.Client()
bot = commands.Bot(command_prefix="!", intents=Intents)

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


@bot.event
async def on_ready():
    print(f"Logged in as {bot.user}")


@bot.event
async def on_message(message):
    username = str(message.author.name)
    user_message = str(message.content)
    channel = str(message.channel.name)
    print("botloggedin as {0.user}".format(client))
    if message.channel.name == "general":
        if user_message.lower() == "!isrunning":
            await message.channel.send("The Bot is currently running")


bot.run(TOKEN)
slate swan
#

Remove client=...

#

Pass actual intents to the bot

#
TOKEN = ""
intents = Intents.default()
intents.messages = True
intents.message_content = True
bot = commands.Bot(command_prefix="!", intents=intents)
regal pulsar
#

editing

slate swan
#

.

marsh thorn
#

eyyy it works

slate swan
#

Ok

slate swan
marsh thorn
#

ty guys

regal pulsar
#

np

quaint epoch
#

is there an event to see when a member is banned?

slate swan
#

Yes

#

!d discord.on_member_ban

unkempt canyonBOT
#

discord.on_member_ban(guild, user)```
Called when user gets banned from a [`Guild`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild "discord.Guild").

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

:(

quaint epoch
#

kek

slate swan
#

That doesn't exist

quaint epoch
#

alr

regal pulsar
#

on_member_ban

slate swan
#

Bit late ๐ŸŒ

#

!late

regal pulsar
slate swan
#

I got first but...

regal pulsar
#

lmao

slate swan
#

Your program is already running, stop it first

#

Xd done

#

Does anyone have any example to make a welcome image with PIL?
I can't seem to figure it out

quaint epoch
#

bow do i check if a member is timed out, i.e updated (on_member_update does not look for timeouts)

quaint epoch
#

!d disnake.on_member_update

unkempt canyonBOT
#

disnake.on_member_update(before, after)```
Called when a [`Member`](https://docs.disnake.dev/en/latest/api.html#disnake.Member "disnake.Member") updates their profile.

This is called when one or more of the following things change:

โ€ข nickname

โ€ข roles

โ€ข pending...
maiden fable
#

Prolly a bug in the Discord API

quaint epoch
#

well, im going to try it

slate swan
#

Hey hunter how are u ๐Ÿ‘‹

maiden fable
#

@pliant gulch u got any insight on this?

maiden fable
modest brook
#

hi

slate swan
#

Hello ๐Ÿ‘‹

#

member return none

#

use member = bot.get_user(id) or await bot.fetch_user(id)

pliant gulch
slate swan
#

AttributeError: 'Member' object has no attribute 'avatar_url_as'
I am trying to make welcome message in PIL

slate swan
#

yep its a coroutine

quaint epoch
#

the docs say it doesn't include timeouts, but it does in the api

quaint epoch
#

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

slate swan
quaint epoch
#

oh i just created an on_member_update event rn

#

and it ran every time i muted someone

slate swan
#

muted? or timed out

quaint epoch
#

timed out

slate swan
#

so the event works...

quaint epoch
#

yes

slate swan
#

coroutines are functions which you need to await

maiden fable
#

@quaint epoch did u test the event?

quaint epoch
#

yes

maiden fable
#

And it isn't dispatched for timeout? @quaint epoch

quaint epoch
#

nope it is

maiden fable
#

So it's dispatching?

quaint epoch
#

yes

#

docs are strange

maiden fable
#

Cool

#

Yea they are outdated

quaint epoch
#

mhm

slate swan
#

use the master branch docs, not stable

quaint epoch
#

it's in my bookmarks, it's going to stay there

olive osprey
#
bot = commands.Bot("beta ",test_guilds=[966350034822135878], sync_commands=True, case_insensitive=True, intents=intents, strip_after_prefix=True)

@bot.slash_command(description="Responds with the user ID.")
async def userid(inter, user: disnake.Member):
    await inter.response.send_message(user.id, ephemeral=True)

Hey, I'm not sure if I just changed something, but this worked 10min ago, and now it just stopped working. Does someone see something wrong?

olive osprey
cloud dawn
#

!d discord.ext.tasks.Loop.next_iteration

unkempt canyonBOT
cloud dawn
#

A loop.

#

Combine it with a database and you're ready.

olive osprey
# cloud dawn You got an error?

Nope, the bot normally runs, everything works, the prefix also works normal but for some reason it just doesn't show me the slash command, as said it did 10 min ago

olive osprey
cloud dawn
olive osprey
#

I just saw in the docs this exists:

sync_commands_debug=True

I'm gonna try that real quick

olive osprey
#

!d discord.Message.add_reaction

unkempt canyonBOT
#

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

Adds a reaction to the message.

The emoji may be a unicode emoji or a custom guild [`Emoji`](https://discordpy.readthedocs.io/en/master/api.html#discord.Emoji "discord.Emoji")...
heady sluice
olive osprey
#

what

slate swan
#

I haven't used the library in a while but I guess if you want to add reaction, then you should "reply" instead of "respond"?

heady sluice
#

you oversaw the error

slate swan
#

By the way hoomans, what is this rate limit thingy?

unkempt canyonBOT
#

5. Do not provide or request help on projects that may break laws, breach terms of services, or are malicious or inappropriate.

slate swan
#

bruh

quaint epoch
#

just to be safe

#

429s/ratelimits are where you send too many requests to the api in a certain period of time, so the wrapper/api temporarily bans you from sending more

#

like spamming d in a server, eventually discord will tell you to be less spicy, which is the ui version of ratelimiting

slate swan
#

Anyway, so my bot was temporarily restricted from using the discord API. When I checked the error, it was because of payload of that raw_reaction_add thingy.

slate swan
#

I can send my code if you want but like how do I get rid of that?

quaint epoch
#

you'll have to wait until the ratelimit is over

slate swan
#

Just check once more if this code is badly designed please.

#
@bot.event
async def on_raw_reaction_add(payload):
    DO = False
    message = await bot.get_channel(payload.channel_id).fetch_message(payload.message_id)
    if message.author.id != 933372954589401158:
        return
    emb = message.embeds[0]
    if payload.member.id == int(emb.footer.text[5:]):
        _reacts = []
        for i in (reacts := message.reactions):
            if i.me:
                if i.emoji == payload.emoji:
                    _special_emoji = str(i.emoji)
                    DO = True
                else:
                    _reacts.append(str(i.emoji))
    if DO:
        await message.delete()
        new_emb = Embed(
            title = "Your remaining tasks in the to-do list:-",
            colour = payload.member.colour
        )
        new_emb.set_author(name = payload.member.name, icon_url = payload.member.avatar_url)
        new_emb.set_footer(text = f"ID:- {payload.member.id}")
        new_emb.set_thumbnail(url = payload.member.avatar_url)
        for fie in emb.fields:
            if fie.name.startswith(_special_emoji):
                new_emb.add_field(name = f"~~{fie.name}~~", value = '\u200b', inline = False)
            else:
                new_emb.add_field(name = fie.name, value = '\u200b', inline = False)
        _rmsg = await message.channel.send(embed = new_emb)
        if not _reacts:
            await message.channel.send(f"Congrats <@{payload.member.id}>! You have finished all your tasks :partying_face:")
            return
        for i in _reacts:
            await _rmsg.add_reaction(i)
#

I guess the code is too confusing especially without any initial detail KEK. Anyway, thanks HRLO.

olive osprey
#

Ok so,

@bot.slash_command(description="hi")
async def hi(inter):
  await inter.response.send_message(f"hi {inter.author}")


@bot.slash_command(description="Developer command.")
async def reloadbot(inter):
  if inter.author.id == 703671503954378782:
    embed = disnake.Embed(title="Sucessfully reloaded bot!", description=f"The cog {cog} has been successfully reloaded.", color=disnake.Colour.green())
    for filename in os.istdir("./cogs"):
      if filename.endswith(".py"):
        bot.load_extension(f"cogs.{filename[:-3]}")
    await inter.response.send_message(embed=embed, ephemeral=True)
  else:
    await inter.response.send_message("a")

For some reason the upper slash command "hi" is working fine, but the other one doesn't. It doesn't even get shown for some reason.

zinc otter
#

with the new update of text channels inside a voice channel

#

how do u get the text channel?

heady sluice
#

what

slate swan
zinc otter
#

here there are none i think

slate swan
zinc otter
#

like this

slate swan
#

my_msg is already a Message object whih has no attribute as message

olive osprey
slate swan
#

my_msg.add_...

olive osprey
#

Yeah, I kinda figured it out, a disnake developer told me that it's an API bug due the discord update or something, I reinstalled it and now it works. Anyways, thanks for trying to help

slate swan
#

what is it?

#

either the message is not being sent

little ivy
#

why do my buttons stop working after like 5 minutes on the same message?

vale wing
#

Is this a giveaway bot

#

If so asyncio.sleep hmmmm

vale wing
#

Most likely due to timeout set on view

sacred oyster
#

What's the difference between asyncio.sleep() & time.sleep()?

vale wing
#

asyncio one is non blocking and time is

#

!blocking

unkempt canyonBOT
#

Why do we need asynchronous programming?
Imagine that you're coding a Discord bot and every time somebody uses a command, you need to get some information from a database. But there's a catch: the database servers are acting up today and take a whole 10 seconds to respond. If you do not use asynchronous methods, your whole bot will stop running until it gets a response from the database. How do you fix this? Asynchronous programming.

What is asynchronous programming?
An asynchronous program utilises the async and await keywords. An asynchronous program pauses what it's doing and does something else whilst it waits for some third-party service to complete whatever it's supposed to do. Any code within an async context manager or function marked with the await keyword indicates to Python, that whilst this operation is being completed, it can do something else. For example:

import discord

# Bunch of bot code

async def ping(ctx):
    await ctx.send("Pong!")

What does the term "blocking" mean?
A blocking operation is wherever you do something without awaiting it. This tells Python that this step must be completed before it can do anything else. Common examples of blocking operations, as simple as they may seem, include: outputting text, adding two numbers and appending an item onto a list. Most common Python libraries have an asynchronous version available to use in asynchronous contexts.

async libraries
The standard async library - asyncio
Asynchronous web requests - aiohttp
Talking to PostgreSQL asynchronously - asyncpg
MongoDB interactions asynchronously - motor
Check out this list for even more!

sacred oyster
#

Non blocking?

vale wing
#

Read the embed above

vale wing
# little ivy

Default timeout of View is 180 seconds, to ignore it, use View(timeout=None) and for this case I recommend using persistent views

#

Also it's better to subclass your views cause that way the code looks cleaner

#

@slate swan dpy 2.0?

#

@slate swan what is the type of ctx

sacred oyster
#

From API

hexed junco
#

Discord.py is out of support, so stuff may not work

daring olive
vale wing
#

@slate swan print(type(ctx))

vale wing
vale wing
brave forge
#

in discord.py version 1.7.3 is it possible to make commands that will do something for a certain amount of time ?

slate swan
maiden fable
regal pulsar
#
    @commands.command()
    @commands.has_permissions(manage_channels=True)
    async def kick(self, ctx: commands.Context, user: Either[disnake.Member, str], *, reason=None):
        if isinstance(user, str):
            for member in ctx.guild.members:
                if user in member.name:
                    await ctx.guild.kick(member)
                    if reason != None:
                        embed = disnake.Embed(
                            description=f"""{user.mention} has been kicked.
            Reason:
            {reason}      
                """,
                        )
                        await ctx.channel.send(embed=embed)
                        embed = disnake.Embed(
                            description=f"""
            You have been kicked from {ctx.guild.name}
            Reason:
            {reason}
                """
                        )
                        await disnake.DMChannel.send(user, embed=embed)
                    else:
                        embed = disnake.Embed(description=f"{user.mention} has been kicked.")
                        await ctx.channel.send(embed=embed)
                    break
            else:
                embed = disnake.Embed(description="User Not Found Onii Chan!")

        elif isinstance(user, disnake.Member):
            await ctx.guild.kick(user)
            if reason != None:
                embed = disnake.Embed(
                    description=f"""{user.mention} has been kicked.
    Reason:
    {reason}      
        """,
                )
                await ctx.channel.send(embed=embed)
                embed = disnake.Embed(
                    description=f"""
    You have been kicked from {ctx.guild.name}
    Reason:
    {reason}
#
        """
                )
                await disnake.DMChannel.send(user, embed=embed)
            else:
                embed = disnake.Embed(description=f"{user.mention} has been kicked.")
                await ctx.channel.send(embed=embed)
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.

regal pulsar
maiden fable
#

It is

slate swan
#

yes but it's glitching out due to discord escape characters

#

so just put it in the paste service, takes like 10 seconds to do so

#

also yeah, indentation is way messed up on discord

regal pulsar
#

k

#

i wanna be able to do something like

#

?kick nyx

#

without mentioning

slate swan
#

how to set security level for serverinfo?

#

you just check a role or something because its definitely not the accounts security level as it would be unsafe

slate swan
#

thats the servers moderation level?

#

yea

regal pulsar
unkempt canyonBOT
slate swan
#

nvm what i said as its a guild

#

thx

#

i thought it was an account shouldve seen the invoke message

regal pulsar
#

lol

#

is there a mention object

slate swan
#

just an attr

regal pulsar
#

yeah but

#

i want to check if a mention is passed in a command or a string

#

like

slate swan
#

!d discord.Message.mentions

unkempt canyonBOT
regal pulsar
#

hmm

slate swan
#

or just have a member argument if you want it to take a member object

stone beacon
#

d.py converters still work though right?

slate swan
#

how to mark the number of people with a certain status?

regal pulsar
slate swan
#

yep

slate swan
#

the converter should work yes

#

how to mark the number of people with a certain status?

regal pulsar
slate swan
regal pulsar
#

and a string if its a string

slate swan
slate swan
#

!d typing.Union

unkempt canyonBOT
#

typing.Union```
Union type; `Union[X, Y]` is equivalent to `X | Y` and means either X or Y.

To define a union, use e.g. `Union[int, str]` or the shorthand `int | str`. Using that shorthand is recommended. Details...
slate swan
#

just use pipes

#

!pep 604

unkempt canyonBOT
#
**PEP 604 - Allow writing union types as ``X | Y``**
Status

Accepted

Python-Version

3.10

Created

28-Aug-2019

Type

Standards Track

regal pulsar
slate swan
#

it would look like py async def command(ctx,arg: typing.Union[Member. str]): ...

regal pulsar
slate swan
regal pulsar
#

but

slate swan
#

what was your issue

#

!rule 4

unkempt canyonBOT
#

4. Use English to the best of your ability. Be polite if someone speaks English imperfectly.

slate swan
#

im not going to use a translator

#

same sorry

brave forge
#

how to make the bot delete its message 30 seconds after sending ?

regal pulsar
slate swan
brave forge
#

@slate swan aren 't you tired of writing the same thing ?

slate swan
#

not really

regal pulsar
regal pulsar
slate swan
#

ctx.channel and .sleep๐Ÿ—ฟ

#

you know that the member converter convers the name and ids as well right?

regal pulsar
#

but lets say i wanted to do

#

?kick sar

slate swan
#

why do a incheck though

ivory cave
#

for how long have yall been programming ?

slate swan
ivory cave
#

curious

regal pulsar
#

my friend wants to be able to do pass a bit of their name in

slate swan
regal pulsar
ivory cave
regal pulsar
#

actually less cuz of exams

slate swan
ivory cave
regal pulsar
#

wow

#

i feel young ๐Ÿ˜ฉ

slate swan
#

sarthak is an old master

ivory cave
regal pulsar
slate swan
#

yes

slate swan
brave forge
#

@regal pulsar@slate swan@slate swan thanks

slate swan
regal pulsar
#

nah

slate swan
#

they are different things

regal pulsar
#

from typing import Union as Either

#

lol

#

it just looks better

slate swan
#

๐Ÿ˜‘ why

#

anyways, what's the issue?

#

your command would need member intents in cause you didnt add it already

regal pulsar
#

not sure how to go about it in general

#

if you mention someone i want a Member object

#

if you just pass in a string it should stay a string

slate swan
#

thats what your code must do, that's the problem>

#

it will always be a string?

slate swan
#

the converter just parses the string for a snowflake or a snowflake inside of the mention format and it makes it an object

slate swan
regal pulsar
#

hmm

brave forge
regal pulsar
#

or what if i dont typehint

slate swan
slate swan
#

why spoonfeed

regal pulsar
slate swan
#

just give him the coroutine that wraps the endpoint

regal pulsar
#

then i try to get a Member object with .get

slate swan
#

!d discord.Member.timeout

unkempt canyonBOT
#

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

Applies a time out to a member until the specified date time or for the
given [`datetime.timedelta`](https://docs.python.org/3/library/datetime.html#datetime.timedelta "(in Python v3.10)").

You must have the [`moderate_members`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.moderate_members "discord.Permissions.moderate_members") permission to
use this...
regal pulsar
#

how exactly does that work

slate swan
#

it works in 3.7 too

regal pulsar
#

ye im on 3.10.4 iirc

slate swan
#

given that you need to import annotations from future

regal pulsar
slate swan
#

yeah

#

with annotations it wouldnt matter what py version

#

ofc it would as yoy need to import the stlib

#

*3.6+

brave forge
#

@regal pulsar thanks

regal pulsar
slate swan
#

yes but it can still be used in 3.6+

brave forge
slate swan
#

add a space or get recked

regal pulsar
#

lol

slate swan
#

slow

#

i already did

#

idk sarthak said it does idk the exact version lol

#

working in 3.7 too

pliant gulch
slate swan
#

my bad

slate swan
regal pulsar
#

now if only i knew what you were talking about ๐Ÿ˜”

slate swan
#

๐Ÿ˜ฟ

pliant gulch
slate swan
#

that acts like a Union

regal pulsar
#

i see

slate swan
#

no

#

it can be used in other things and not ony type hint

#

what did you said

#

its literally the same thing

#

its just bitwise or

slate swan
#

๐Ÿ™€

#

stawp

sage otter
#

pipes are cool

regal pulsar
#

can someone tell me what this is

pliant gulch
#

The return annotation

sage otter
#

A annotation

regal pulsar
#

the ->

pliant gulch
#

Denoting that that method, returns None

ivory cave
#

ik its something from JS but not sure

regal pulsar
#

i see it everywhere

pliant gulch
#

!e ```py
def foo() -> str:
return "bar"

def baz() -> None:
...

unkempt canyonBOT
#

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

[No output]
ivory cave
sage otter
#

You see it a lot in well written code

pliant gulch
slate swan
sage otter
#

Good python programmers type/annotate their code

slate swan
ivory cave
#

but what does it mean tho? ive never even heard of it and ive been programming for some solid months

sage otter
#

He just said above

pliant gulch
#

It's for type safety

sage otter
#

Type safety?

#

Oh

pliant gulch
#

Yes, you want to know the types of your variables, etc

sage otter
#

Yea.

pliant gulch
#

It's good to know them, and it stops a lot of problems before they happen

slate swan
#

not only typehints* it can be used in other things aswell

regal pulsar
ivory cave
pliant gulch
#

Yes it's like a comment

regal pulsar
#

print func in python

ivory cave
slate swan
#

its sorta like a comment ig

pliant gulch
#

The interpreter doesn't parse annotations at all

ivory cave
slate swan
pliant gulch
slate swan
regal pulsar
#

thats actually why i started typehinting

slate swan
#

its quite useful without your editor showing its unknown

regal pulsar
#

way cleaner

slate swan
#

and sometimes depending on the types the editor wont highlight the syntax of methods i.e since it doesnt knoe the type

stone beacon
#

A fellow ayu theme user?

sage otter
#

just get good and work without the intellisense. All that matters is runtime.

regal pulsar
#

plus

stone beacon
#

Mi gusta

regal pulsar
glad cradle
regal pulsar
#

i cant live without this

ivory cave
stone beacon
#

what colour scheme are ya using?

pliant gulch
stone beacon
#

Looks liike ayu mirage

unkempt canyonBOT
#

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

Foo bar
slate swan
#

ok?

pliant gulch
#

Saying or operator is equivalent to typing.Union is miss-leading imo

#

You should just reference it as a union between the types, operator makes it sound like it does an operation

slate swan
#
@commands.command()
  async def ping(self, ctx):
    message = await embed.add_field(name="`Pinging...`")
    await embed.add_field(name=f"**Latency is** ``{round(self.bot.latency * 1000)}``**ms**")
stone beacon
#

Can't rmr the last time I touched Union after they allowed us to do X | Y in 3.10

slate swan
#

Correct?

slate swan
#

i never touched Union๐Ÿ˜ณ

slate swan
regal pulsar
#

ah

pliant gulch
#

I've always hated the typing module

slate swan
#

dont you use it allot๐Ÿ˜ฟ

pliant gulch
#

I just want a non-library way to type hint ๐Ÿ˜”

regal pulsar
#

wait

slate swan
#

yeah i agree

pliant gulch
#

I only use it cause I'm forced to, like before when list wasn't generic

regal pulsar
#

isnt type hinting just

#
@bot.command()
async def test(ctx: commands.Context):
    pass

pliant gulch
regal pulsar
#

or do i have it completely wrong

slate swan
#

it would be nice to have Callable i.e built in without importing typing ๐Ÿ˜”

stone beacon
#

^^^^^^^^^^^^^^^^^^^^^^^^^^^^

regal pulsar
#

whats Callable ๐Ÿ’€

pliant gulch
#

That already exists with typing_extensions

slate swan
pliant gulch
#

You only really need self in causes of generics anyways so, most people won't be using them

slate swan
#

its just the type lol

pliant gulch
#

No?

regal pulsar