python discord2.0.1 新功能小试

安装discord2

# 如果有旧discordpy 删除
pip uninstall discord.py
# 安装新库
python3 -m pip install py-cord

用的类调用

main.py

import discord
from discord.ext import commands
intents = discord.Intents.all()
bot = commands.Bot(command_prefix='!', intents=intents)
# 申请token
token = '*****'
if __name__ == '__main__':
    bot.load_extension('CMDS')
    bot.run(token)

CMDS.py

import asyncio
import discord
from discord.ext import commands

# 单独服务器,服务工会id,只适合单独工会
guild_id = 1232321121


class CogExtension(commands.Cog):
    def __init__(self, bot: commands.Bot):
        self.bot = bot
        self.guild = None

    @commands.Cog.listener()
    async def on_ready(self):
        self.guild = get_guild(bot)
        print('on_ready')


def get_guild(bot):
    guild = None

    for i in bot.guilds:
        # 服务器id 
        if i.id == guild_id:
            guild = i
            continue
    return guild



class CMD(CogExtension):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        async def interaction_button():
                await self.bot.wait_until_ready()  # 等待bot就绪
                await asyncio.sleep(1)
                while not self.bot.is_closed():
                    if self.guild:
                        interaction = await self.bot.wait_for("interaction")

                        print("interaction", interaction.custom_id)
                        if interaction.custom_id == 'button-ephemeral-true':
                            await interaction.response.send_message("button-ephemeral-true", ephemeral=True)
                        elif interaction.custom_id == 'button-ephemeral-false':
                            await interaction.response.send_message("button-ephemeral-false", ephemeral=False)
                        # else:
                        #     await interaction.edit_original_message(content='edit')
        self.bot.loop.create_task(interaction_button())

    # 错误处理
    @commands.Cog.listener()
    async def on_command_error(self, ctx, error):
        pass

    @commands.command(name='ping')
    async def ping(self, ctx):
        await ctx.send("pong")

    # 发送带有按钮的消息
    @commands.command(name='send-message-button-true')
    @commands.check(is_team)
    async def send_msg_button_true(self, ctx):
        item = discord.ui.Button(custom_id='button-ephemeral-true', label='button-ephemeral-true')

        view = discord.ui.View()
        view.add_item(item)
        try:
            await ctx.send("team pong", view=view)
        except Exception as e:
            print(e)
            
    # 发送带有按钮的消息
    @commands.command(name='send-message-button-false')
    @commands.check(is_team)
    async def send_msg_button_false(self, ctx):
        item = discord.ui.Button(custom_id='button-ephemeral-false', label='button-ephemeral-false')

        view = discord.ui.View()
        view.add_item(item)
        try:
            await ctx.send("team pong", view=view)
        except Exception as e:
            print(e)

    # 斜杠命令 /
    # guild_ids 匹配的工会id列表  description 简介 name 指令名称,如果没有就是函数名
    @commands.slash_command(name='hello-respond', guild_ids=[guild_id], description='hello')
    async def hello_respond(self, ctx, member: discord.Member, age: int):
        # 类似回复指令
        await ctx.respond(f"Hello respond, {member}, age{age}!")

    @commands.command(name='hello-send', guild_ids=[guild_id], description='hello')
    async def hello_send(self, ctx, member: discord.Member, age: int):
        # 类似回复指令
        await ctx.send(f"Hello respond, {member}, age{age}!")

调用 !send-message-button-true 指令,点击按钮消息只能本人看到

 调用指令!send-message-button-false,返回信息公共可以看到

 

 

 还有定时任务等功能有机会在写

测试了一下 这段代码有点问题·interaction_button·把这个函数删了,改成对象方法

class CMD(CogExtension):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        # async def interaction_button():
        #     await self.bot.wait_until_ready()  # 等待bot就绪
        #     await asyncio.sleep(1)
        #     while not self.bot.is_closed():
        #         if self.guild:
        #
        #
        # self.bot.loop.create_task(interaction_button())


    @commands.Cog.listener()
    async def on_interaction(self, interaction):
        pass  # 之前方法里的逻辑

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Python中,你可以使用discord.py来创建和管理Discord机器人。discord.py是一个用于与Discord API进行交互的强大。你可以使用它来创建和管理服务器、频道、角色以及与用户进行交互。 在你提供的引用中,是一个使用discord.py 1.3.4版本的解决方案的示例代码。这段代码展示了如何在Discord机器人中添加角色给特定用户。 首先,你需要获取你的服务器的ID,可以使用`bot.get_guild(你的服务器id)`来获取服务器对象。然后,你可以使用`discord.utils.get(guild.roles, name="你的role Name")`来获取特定名称的角色对象。 接下来,你可以使用`bot.http.add_role(guild_id=guild.id, role_id=role.id, user_id=data\["user_id"\])`来将角色添加给特定的用户。这个方法会向Discord API发送请求来执行这个操作。 请注意,这只是一个示例代码,你需要根据你的具体需求进行适当的修改和调整。 总结起来,使用discord.py可以方便地在Python中创建和管理Discord机器人,并与Discord API进行交互。你可以使用这个来实现各种功能,包括添加角色给特定用户。 #### 引用[.reference_title] - *1* [python discord.py重写 bot add role](https://blog.csdn.net/qq_34081968/article/details/116669833)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control,239^v4^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值