unofficial library for discord components(on development)

Overview

discord.py-buttons

Build Status PyPI version Documentation Status

unofficial library for discord buttons(on development)

Install

pip install --upgrade discord_buttons

Example

from discord import Client
from discord_buttons import DiscordButton, Button, ButtonStyle, InteractionType

bot = Client()
ddb = DiscordButton(bot)

@bot.event
async def on_message(msg):
    m = await msg.channel.send(
        "Content",
        buttons=[
            Button(style=ButtonStyle.blue, label="Blue"),
            Button(style=ButtonStyle.red, label="Red"),
            Button(style=ButtonStyle.URL, label="url", url="https://example.org"),
        ],
    )

    res = await ddb.wait_for_button_click(m)
    await res.respond(
        type=InteractionType.ChannelMessageWithSource,
        content=f'{res.button.label} clicked'
    )


bot.run("token")

Docs

The docs can contain lot of spelling mistakes, grammar errors so if there is a problem please create an issue!

Features

  • Send, Edit button messages
  • Get button click event!
  • Supports discord.ext.commands

Helps

  • Minibox - Button API explanation
  • Lapis - Told me how to replace a property
Comments
  • [Bug] Very high message roundtrip ping when the lib is loaded.

    [Bug] Very high message roundtrip ping when the lib is loaded.

    Bug Line

    I don't know where is the actual bug. My bot is over 8000 servers.

    image After a bot restart with the Cog unloaded the bot works fine. When I load the Cog it slows down.

    Excpected Action

    Just work

    Actual Action

    Well it works but slows down the bot.

    Reproducing the action

    Module loaded in a Cog:

        def __init__(self, client):
            self.client = client
            self.connection = client.dbconnection
            if not hasattr(client, "component_client"):
                self.component_client = DiscordComponents(client)
            else:
                self.component_client = client.component_client
    

    Also it is present in my on_ready() function as well. The cog loads when the bot is ready.

    Possible Solution

    I didn't manage to find anything.

    Environment

    • Python v3.8.5-final
    • discord.py v1.7.2-final
    • aiohttp v3.6.2
    • system info: Linux 5.4.0-73-generic #82-Ubuntu SMP Wed Apr 14 17:39:42 UTC 2021 Latest version of the lib from GitHub.

    Check

    • [x] Are you using the newest version?
    • [ ] Is this bug related to security issues?
    bug 
    opened by FightMan01 21
  • [Bug] Error when adding component to message

    [Bug] Error when adding component to message

    Bug Line

    Ignoring exception in command button:
    Traceback (most recent call last):
      File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 85, in wrapped
        ret = await coro(*args, **kwargs)
      File "main.py", line 29, in button
        await ctx.send("Buttons!", components=[Button(label="Button", custom_id="button1")])
      File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord_slash/dpy_overrides.py", line 323, in send_override
        return await send(channel, *args, **kwargs)
      File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord_slash/dpy_overrides.py", line 300, in send
        data = await state.http.send_message(
      File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/http.py", line 156, in request
        kwargs['data'] = utils.to_json(kwargs.pop('json'))
      File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/utils.py", line 328, in to_json
        return json.dumps(obj, separators=(',', ':'), ensure_ascii=True)
      File "/usr/lib/python3.8/json/__init__.py", line 234, in dumps
        return cls(
      File "/usr/lib/python3.8/json/encoder.py", line 199, in encode
        chunks = self.iterencode(o, _one_shot=True)
      File "/usr/lib/python3.8/json/encoder.py", line 257, in iterencode
        return _iterencode(o, 0)
      File "/usr/lib/python3.8/json/encoder.py", line 179, in default
        raise TypeError(f'Object of type {o.__class__.__name__} '
    TypeError: Object of type Button is not JSON serializable
    
    The above exception was the direct cause of the following exception:
    
    Traceback (most recent call last):
      File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 939, in invoke
        await ctx.command.invoke(ctx)
      File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 863, in invoke
        await injected(*ctx.args, **ctx.kwargs)
      File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 94, in wrapped
        raise CommandInvokeError(exc) from exc
    discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: Object of type Button is not JSON serializable
    

    Expected Action

    What did you expect the module to do? Send a message with a button when the button command is executed

    Actual Action

    What actually happened? It throwed an discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: Object of type Button is not JSON serializable exception

    Reproducing the action

    How could you reproduce the action?

    from discord_components import DiscordComponents,InteractionEventType,ComponentsBot,Button
    
    TOKEN="bot token"
    
    client=ComponentsBot(command_prefix="?",help_command=None)
    
    @client.event
    async def on_ready():
        print("ready")
    
    @client.command()
    async def button(ctx):
        await ctx.send("Buttons!", components=[Button(label="Button", custom_id="button1")])
        interaction = await client.wait_for(
            "button_click", check=lambda inter: inter.custom_id == "button1"
        )
        await interaction.send(content="Button Clicked")
        
    client.run(TOKEN)
    

    Possible Solution

    How do you think you can fix this bug? Make the button class JSON serializable.

    Environment

    What is the version of the python? python 3.8.3

    Check

    • [x] Are you using the newest version?
    • [ ] Is this bug related to security issues?
    bug 
    opened by Markos-Th09 10
  • [Bug] Button Command within cogs

    [Bug] Button Command within cogs

    Hello, i now sucessfully made buttons working in the mainfile. now im trying to get it into cogs and used a examplecode in the examplefolder on this githubpage. However i get a dumb issure. I will provide the code im using and the error that appears when running the command below:

    Ignoring exception in on_socket_response
    Traceback (most recent call last):
      File "D:\Downloads\Python\python 3.8.7\lib\site-packages\discord\client.py", line 343, in _run_event
        await coro(*args, **kwargs)
      File "D:\Downloads\Python\python 3.8.7\lib\site-packages\discord_components\client.py", line 79, in on_socket_response
        event = self._events.get(res["d"]["data"]["component_type"], None)
    KeyError: 'component_type'
    An exception has occurred while executing command `button`:
    Traceback (most recent call last):
      File "D:\Downloads\Python\python 3.8.7\lib\site-packages\discord_slash\client.py", line 744, in invoke_command
        await coro
      File "D:\Downloads\Python\python 3.8.7\lib\site-packages\discord_slash\model.py", line 227, in invoke
        return await self.func(self.cog, *args, **kwargs)
      File "D:\my_python_projects\MongoDB Test\Cogs\music.py", line 537, in buttontest
        await ctx.send(
    TypeError: send() got an unexpected keyword argument 'components'
    
        @cog_ext.cog_slash(name="button", guild_ids=slash_ids)
        async def buttontest(self, ctx):
            await ctx.send(
                "Here is an example of a button",
                components=[
                    [
                        Button(style=ButtonStyle.green, label="GREEN"),
                        Button(style=ButtonStyle.red, label="RED"),
                        Button(style=ButtonStyle.grey, label="GREY", disabled=True),
                    ],
                    Button(style=ButtonStyle.blue, label="BLUE"),
                    Button(style=ButtonStyle.URL, label="URL", url="https://www.example.com"),
                ],
            )
    
    bug 
    opened by FeelsBadMan1 9
  • Add example a command(buttons navigations) with while and check

    Add example a command(buttons navigations) with while and check

    PR TYPE

    Why did you open this PR (If it is other, please write a more detailed description.)

    • [x] New feature
    • [ ] Fix bug
    • [ ] Typo
    • [ ] Other

    Checks

    • [ ] Did you use the black formatter?
    • [ ] Does this requires the users to change their code?
    • [ ] Did you test?
    • [ ] Have you updated the docs?
    • [ ] Can you listen to our requests?
    • [ ] Did you use conventional commits
    opened by helish88 7
  • Create simple.py

    Create simple.py

    PR TYPE

    Added example file. I'm planning to add more examples like calculator, etc

    Why did you open this PR (If it is other, please write a more detailed description.)

    • [ ] New feature
    • [ ] Fix bug
    • [ ] Typo
    • [x] Other

    Checks

    • [ ] Did you use the black formatter?
    • [ ] Does this requires the users to change their code?
    • [x] Did you test?
    • [ ] Have you updated the docs?
    • [x] Can you listen to our requests?
    • [ ] Did you use conventional commits
    opened by notnotrachit 7
  • Examples not working[Bug]

    Examples not working[Bug]

    Hi! I am trying the examples and the buttons are created but I am always getting "This interaction failed", I am using the last version of the library and Python 3.10.

    bug 
    opened by nfernandezsanz 6
  • Use add_listener function instead of on_socket_response

    Use add_listener function instead of on_socket_response

    In this line, I think the intention is add a socket_response listener https://github.com/kiki7000/discord.py-components/blob/49dafb8f5efa84c655649608b7ffd157b86d0040/discord_components/client.py#L86

    However, an unwanted side effect of this way of adding a listener is that it overwrites any other on_socket_response listener function already defined on the bot. I think a better solution would be to use discord.py's Bot.add_listener function:

    self.bot.add_listener(on_socket_response, name='socket_response')
    

    This listener will still be called even if some other library/user adds 'socket_response' listeners, and also won't replace existing on_socket_response methods.

    opened by burtonwilliamt 5
  • [Bug] Bot mentions regardless of its AllowedMentions

    [Bug] Bot mentions regardless of its AllowedMentions

    Excpected Action

    I've set its allowed_mentions to discord.AllowedMentions.none() and expects it not to mention anyone.

    Actual Action

    It mentions as if no filter is applied.

    Reproducing the action

    set its allowed_mentions to discord.AllowedMentions.none() declare DiscordComponents with change_discord_methods = True reply to a message

    Possible Solution

    It is happening when change_discord_methods is enabled. It is surely to cause of this issue.

    Environment

    3.9 library: most recent

    Check

    • [x] Are you using the newest version?
    • [ ] Is this bug related to security issues?
    bug 
    opened by seojin200403 4
  • [Bug] When fetching the buttons of a message, it doesn't return their rows.

    [Bug] When fetching the buttons of a message, it doesn't return their rows.

    Bug Line

    https://github.com/kiki7000/discord.py-components/blob/master/discord_components/client.py

    Excpected Action

    Return the list of buttons with the rows ([[Button1, Button2, Button3, Button4, Button5], [Button6]])

    Actual Action

    It returns a single list of buttons ([Button1, Button2, Button3, Button4, Button5, Button6])

    Reproducing the action

    Fetch a message with more than one row of buttons

    Possible Solution

    Provide the rows

    Environment

    Python 3.9.5

    Check

    • [X] Are you using the newest version?
    • [ ] Does this bug occurs security issues?
    bug 
    opened by Kanin 4
  • [Bug] Discord Buttons & Components

    [Bug] Discord Buttons & Components

    Hey. today discord released the buttons but somehow i find 2 codeexamples in the docs one use buttons and one use components. if i use the components exaple i get a json not seziable error and if i use buttons i get this:

    Ignoring exception in on_message
    Traceback (most recent call last):
      File "D:\Downloads\Python\python 3.8.7\lib\site-packages\discord\client.py", line 343, in _run_event
        await coro(*args, **kwargs)
      File "D:/my_python_projects/MongoDB Test/mongosetup.py", line 31, in on_message
        m = await msg.channel.send(
      File "D:\Downloads\Python\python 3.8.7\lib\site-packages\discord_buttons\client.py", line 57, in send_button_msg_prop
        return await self.send_button_msg(ctxorchannel, *args, **kwargs)
      File "D:\Downloads\Python\python 3.8.7\lib\site-packages\discord_buttons\client.py", line 150, in send_button_msg
        data = await self.bot.http.request(
      File "D:\Downloads\Python\python 3.8.7\lib\site-packages\discord\http.py", line 192, in request
        async with self.__session.request(method, url, **kwargs) as r:
    AttributeError: 'NoneType' object has no attribute 'request'
    

    anyone knows a solution?

    bug 
    opened by FeelsBadMan1 4
  • Hacktoberfest

    Hacktoberfest

    Can you please add hacktoberfest topic in this repository so that contributors can participate in that by contributing in the repository and pr for this repository can be considered for the participation.

    opened by TheShubhendra 3
Releases(2.1.2)
Utility for downloading fanfiction in bulk from the Archive of Our Own

What is this? This is a program intended to help you download fanfiction from the Archive of Our Own in bulk. This program is primarily intended to wo

73 Dec 30, 2022
Easy and simple, Telegram Bot to Show alert when some edits a message in Group

Edit-Message-Alert Just a simple bot to show alert when someone edits a message sent by them, Just 17 Lines of Code These codes are for those who incu

Nuhman Pk 6 Dec 15, 2021
An example of a chatbot with a number-based menu that can be used as a starting point for a project.

NumMenu Bot NumMenu Bot is an example chatbot showing a way to design a number-based menu assistant with Rasa. This type of bot is very useful on plat

Derguene 19 Nov 14, 2022
Auto-Approved-Bot - Auto Approved Invaite Link Request Telegram Bot

🤖 𝗔𝘂𝘁𝗼-𝗔𝗽𝗽𝗿𝗼𝘃𝗲-𝗕𝗼𝘁 🤖 ℹ️ 𝗨𝘀𝗲𝗴𝗲 ℹ️ When a join request invita

Muhammed 32 Dec 18, 2022
A Python Library to interface with Tumblr v2 REST API & OAuth

Tumblpy Tumblpy is a Python library to help interface with Tumblr v2 REST API & OAuth Features Retrieve user information and blog information Common T

Mike Helmick 125 Jun 20, 2022
pokemon-colorscripts compatible for mac

Pokemon colorscripts some scripts to print out images of pokemons to terminal. Inspired by DT's colorscripts compilation Description Prints out colore

43 Jan 06, 2023
Cryptocurrency Trading Bot - A trading bot to automate cryptocurrency trading strategies using Python, equipped with a basic GUI

Cryptocurrency Trading Bot - A trading bot to automate cryptocurrency trading strategies using Python, equipped with a basic GUI. Used REST and WebSocket API to connect to two of the most popular cry

Francis 8 Sep 15, 2022
A simple Discord bot that can fetch definitions and post them in chat.

A simple Discord bot that can fetch definitions and post them in chat. If you are connected to a voice channel, the bot will also read out the definition to you.

Tycho Bellers 4 Sep 29, 2022
A file-based quote bot written in Python

Let's Write a Python Quote Bot! This repository will get you started with building a quote bot in Python. It's meant to be used along with the Learnin

1 Jan 15, 2022
AWS Blog post code for running feature-extraction on images using AWS Batch and Cloud Development Kit (CDK).

Batch processing with AWS Batch and CDK Welcome This repository demostrates provisioning the necessary infrastructure for running a job on AWS Batch u

AWS Samples 7 Oct 18, 2022
Telegram Group Manager Bot + Userbot Written In Python Using Pyrogram.

Telegram Group Manager Bot + Userbot Written In Python Using PyrogramTelegram Group Manager Bot + Userbot Written In Python Using Pyrogram

1 Nov 11, 2021
💖 Telegram - Telethon - UserBot 💖

『᭙ꪖ᥅ƺẞø†』 🇮🇳 ⚡ ᭙ꪖ᥅ƺBot Is One Of The Fastest & Smoothest Bot On Telegram Based on Telethon ⚡ Status Of Bot Telegram 🏪 YouTube 📺 Dєρℓογ το нєяοκυ D

Team WarZ 1 Mar 28, 2022
Bulk NFT uploader to OpenSea!

Bulk NFT Uploader Description Simple easy peasy python script which logins to opensea account using metamask and bulk uploads NFT to your default coll

Lakshya Khera 25 May 23, 2022
A powerful discord bot for forming team.

Discord_SquadBot A powerful discord bot for forming team. Pre-requirement Python 3.7 and latest Discord.py module is required. Installation guideline

Jacky Yu 2 Jan 29, 2022
Discord Account Generator that will create Account with hCaptcha bypass. Using socks4 proxies

Account-Generator [!] This was made for education. Please use socks4 proxies for nice experiences. [!] Please install these modules - "pip3 install ht

RyanzSantos 10 Feb 23, 2022
User-Bot for reporting russian propaganda channels

Юзер-Бот, що автоматизує репортування Телеграм каналів пропагандистів Цей Телеграм Юзер-Бот використовується для автоматизації репорту пропагандистьск

58 Nov 07, 2022
A script to forward mass number of media to another group/channel. Heroku deploy

Telegram Forward Script 😇 This is a Script to Forward Large Number of Files to Another Telegram Channel. Star එකක් දාල fork එකක් ගහපියව් 🥴 If You Tr

Anjana Madu 17 Oct 21, 2022
A Discord Token Spammer, multi webhooks compatibility, made in python +3.7. By Ezermoz

DiscordWebhookSpammer A Discord Token Spammer, multi webhooks compatibility, made in python +3.7. By Ezermoz Put you webhook in webhooks.txt if you wa

3 Nov 24, 2021
This Discord bot is to give timely notifications to Students in the Lakehead CS 2021 Guild

Discord-Bot Goal of Project The purpose of this Discord bot is to give timely notifications to Students in the Lakehead CS 2021 Guild. How can I contr

8 Jan 30, 2022
API which returns cusswords , can be used to check cusswords in bots etc.

Anti-abuse-api-flask API which returns cusswords , can be used to check cusswords in bots etc. Run pip install -r requirements.txt py app.py API Endpo

8 Jan 03, 2023