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)
A simple telegram bot to help you to remove forward tag from post from any messages . Maded in python3 using @Pyrogram . Developed by @Kunal-Diwan

Frwd-Tag-Remover Telegram Bot to Remove forward tag from any Post . If you need any more modes in repo or If you find out any bugs, mention in @Develo

Kunal Diwan 2 Oct 14, 2022
A Telegram Bot to display Codeforces Contest Ranklist

CFRankListBot A bot that displays the top ranks for a Codeforces contest. Participants' Details All the details of a participant is in the utils/__ini

Code IIEST 5 Dec 25, 2021
Azure Neural Speech Service TTS

Written in Python using the Azure Speech SDK. App.py provides an easy way to create an Text-To-Speech request to Azure Speech and download the wav file.

Rodney 1 Oct 11, 2021
SEBUAH TOOLS CRACK FACEBOOK & INSTAGRAM DENGAN FITUR YANGMENDUKUNG

SEBUAH TOOLS CRACK FACEBOOK & INSTAGRAM DENGAN FITUR YANGMENDUKUNG

Jeeck X Nano 1 Dec 27, 2021
Pybt: a BaoTa panel python sdk

About Pybt is a BaoTa panel python sdk. Pybt 是一个宝塔面板API的Python版本sdk封装库。 公司很多服务器都装了宝塔面板,通过宝塔来部署、安装、维护一些服务,服务器的数量上以后,导致了维护的不方便,这个时候就想使用宝塔提供的API来开发一个运维平台

Adam Zhang 9 Dec 05, 2022
Halcyon is a Matrix bot library created with the intention of being easy to install and use. Inspired by discord.py

Halcyon is a Matrix bot library with the goal of being easy to install and use. The library takes inspiration from discord.py and the Slack li

Wes Ring 19 Jan 06, 2023
Follow pixiv account from twitter profile

Follow pixiv account from twitter profile

Genshi 7 Apr 11, 2022
A simple Facebook Account generator, written in python (needs different Email so Accounts do not get banned)

FacebookAccountGenerator FAB is a Facebook-Account generating script, written in python Installation Use the package manager pip to install selenium p

MrOverload 7 Jan 05, 2023
nuub-bot is a multi-purpose designed and developed in python3

nuub-bot About Nuub-Bot is an open source, fully customizable Discord bot that is constantly growing. You can invite it to your Discord server using t

Baneet Parmar 8 Jun 28, 2022
Opasium AI was specifically designed for the Opasium Games discord only. It is a bot that covers the basic functions of any other bot.

OpasiumAI Opasium AI was specifically designed for the Opasium Games discord only. It is a bot that covers the basic functions of any other bot. Insta

Dan 3 Oct 15, 2021
This bot will automatically like and follow users that post under a specified hashtag

Instagram-bot This bot will automatically like and follow users that post under a specified hashtag Dependencies Java JDK Selenium Updated version of

Makana Edwards 1 Nov 04, 2021
PyMed is a Python library that provides access to PubMed.

IMPORTANT NOTE: I don't have time to maintain this library (as some of you might have noticed). The PubMed API is a little chaotic, without a clear do

Gijs Wobben 143 Dec 21, 2022
A simple python script to send files into your telegram Bot form your PC, Server etc.

telegramSend A simple python script to send files into your telegram Bot form your PC, Server etc. How to Use Install requirements.txt pip3 install -r

Ajay Kumar Tekam 1 Jul 19, 2022
Texting service to receive current air quality conditions and maps, powered by AirNow, Twilio, and AWS

The Air Quality Bot is generally available by texting a zip code (and optionally the word "map") to (415) 212-4229. The bot will respond with the late

Alex Laird 8 Oct 16, 2022
Droplink URL Shortener Bot, deployable to Heroku and Railway.

Droplink-bot Make short link by using Droplink API key. Made by @dakshy. Installation The Easy Way Required Variables BOT_TOKEN: Create a bot using @B

ToonsHub 5 Jun 25, 2022
A Telegram Userbot to play Audio and Video songs / files in Telegram Voice Chats.

VC UserBot A Telegram Userbot to play Audio and Video songs / files in Telegram Voice Chats. It's made with PyTgCalls and Pyrogram Requirements Python

조던 1 Nov 29, 2021
Бот для мини-игры "Рабы" ("Рабство") ВКонтакте.

vk-slaves-bot Бот для мини-игры "Рабы" ("Рабство") ВК Группа в ВК, в ней публикуются новости и другая полезная информация. У группы есть беседа, в кот

Almaz 80 Dec 17, 2022
Discord Bot for SurPath Hub's server

Dayong Dayong is dedicated to helping Discord servers build and manage their communities. Multipurpose —lots of features, lots of automation. Self-hos

SurPath Hub 6 Dec 18, 2021
A simple waybar module to display the status of the ICE you are currently in using the ICE Portals JSON API.

waybar-iceportal A simple waybar module to display the status of the ICE you are currently in using the ICE Portals JSON API. Installation Ensure pyth

Moritz 7 Aug 26, 2022
The most annoying bot on Discord

FBot The most annoying bot on discord Features Lots of fun stuff Message responses, sort of our main feature, no big deal. FBot can respond to a wide

Jude 33 Jun 25, 2022