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)
This package accesses nitrotype's official api along with its unofficial user api

NitrotypePy This package accesses nitrotype's official api along with its unofficial user api. Currently still in development. Install To install, run

The Moon That Rises 2 Sep 04, 2022
A VCVideoPlayer Bot for Telegram made with 💞 By @ProErrorXD

VC Video Player How To Host ✨ Heroku Deploy ✨ The easiest way to deploy this Bot is via Heroku. Credit 🔥 |🇮🇳 Louis |🇮🇳 Sammy |🇮🇳 Blaze Marsha

丂ムᄊᄊƳ 95 May 17, 2022
Data from popular CS:GO website hltv.org

Welcome to hltv-data 👋 🎮 Data from popular CS:GO website hltv.org Install pip install hltv-data Usage The public methods can be reached using HLTVCl

Dariusz Choruży 28 Dec 23, 2022
A project in order to analyze user's favorite musics, artists and genre

Spotify-Wrapped This is a project about Spotify Wrapped (which is an extra option for premium accounts, but you don't need to be premium here) This pr

Hossein Mohseni 19 Jan 04, 2023
A modular Telegram Python bot running on python3 with a sqlalchemy, redis, telethon.

GilbertAnimeBot A modular Telegram Python bot running on python3 with a sqlalchemy, redis, telethon. How to setup/deploy. Read these notes carefully b

Kishore 1 Jan 23, 2022
checks anilist for available usernames (200rq/s)

Anilist checker Running the program Set a path to the extracted files Install the packages with pip install -r req.txt Run the script by typing python

gxzs 1 Oct 13, 2021
IOGen - An Open source discord token generator

_____ ____ _____ |_ _/ __ \ / ____| | || | | | |

0xVichy#1234 85 Nov 03, 2022
A Telegram Video Watermark Adder Bot in Pyrogram by @AbirHasan2005

Watermark-Bot A Telegram Video Watermark Adder Bot by @AbirHasan2005 Features: Save Custom Watermark Image. Auto Resize Watermark According to Video q

Abir Hasan 95 Nov 20, 2022
A Telegram Repo For Devs To Controll The Bots Under Maintenance.This Bot Is For Developers, If Your Bot Is Down, Use This Repo To Give Your Dear Subscribers Some Support By Providing Them Response.

Maintenance Bot A Telegram Repo For Devs To Controll The Bots Under Maintenance About This Bot This Bot Is For Developers, If Your Bot Is Down, Use Th

Vɪᴠᴇᴋ 47 Dec 29, 2022
An API wrapper for Discord written in Python.

HCord A fork of discord.py project. HCord is a modern, easy to use, feature-rich, and async ready API wrapper for Discord written in Python. Key Featu

HCord 0 Jul 30, 2022
Creates Spotify playlists from Spinitron playlists.

spin2spot Creates Spotify playlists from Spinitron playlists. Quick Start You can use spin2spot as a command-line tool: Erik Didriksen 1 Aug 28, 2021

The raid botnet for Telegram

telegram-raid-botnet The raid botnet for Telegram Что нужно сделать перед запуском? Установить модули pip3 install -r requirements.txt Добавить аккаун

Maxim 68 Jan 03, 2023
Instrument asyncio Python for distributed tracing with AWS X-Ray.

xraysink (aka xray-asyncio) Extra AWS X-Ray instrumentation to use distributed tracing with asyncio Python libraries that are not (yet) supported by t

Gary Donovan 12 Nov 10, 2022
High-Resolution Differential Z-Belt Mod for V0 (with optional Kirigami support)

V0-DBM This is a high-resolution differential pulley system belt mod for the Z-axis on Voron 0 with optional Kirigami Bed support. NOTE: Alpha version

Simon Küppers 11 Jan 07, 2023
A MassDM selfbot which is working in 2021

mass-dm-discord - Little preview of the Logger and the Spammer Features Logging User IDS Sending DMs to the logged IDs Blacklist IDs (add the ID of th

karma.meme 88 Dec 26, 2022
An Open Source ALL-In-One Telegram RoBot, that can do lot of things.

An Open Source ALL-In-One Telegram RoBot, that can do lot of things.

JOBIN 0 Dec 01, 2021
Customizable and open-sourced bot for a few private servers

MarlBot A private bot for controlling monkeys and turtles. Why does this bot exist? The bot exists as a general-purpose community bot for a select few

KR 1 Jan 18, 2022
Tamil Voicechat UserBot. Powerd By TamilBots. Https://T.me/TamilSupport

Tamil Voicechat UserBot A Telegram UserBot to Play music 🎶 in Voice Chats. It's recommended to use an USA number.(if your real number is suspended I'

Tamil Bots 78 Nov 01, 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
First Party data integration solution built for marketing teams to enable audience and conversion onboarding into Google Marketing products (Google Ads, Campaign Manager, Google Analytics).

Megalista Sample integration code for onboarding offline/CRM data from BigQuery as custom audiences or offline conversions in Google Ads, Google Analy

Google 76 Dec 29, 2022