如何使用discord.py实现Discord群聊加人、退群等群管理操作
前置说明
以下实现适配discord.py v2.x版本,如使用旧版本需对应调整API。注:使用用户账号作为自机器人运行代码违反Discord服务条款,可能导致账号封禁,建议使用官方认证的机器人账号进行开发。
1. 拉指定好友进入群聊
1.1 群DM场景(需互为好友)
需先获取群DM的GroupChannel对象,以及待添加好友的User对象,示例指令:
@bot.command() async def add_to_group(ctx, user: discord.User): if not isinstance(ctx.channel, discord.GroupChannel): await ctx.send("当前指令仅可在群DM中使用") return try: await ctx.channel.add_recipient(user) await ctx.send(f"已成功将{user.mention}加入群聊") except Exception as e: await ctx.send(f"添加失败:{str(e)}")
1.2 普通服务器场景
需生成服务器邀请链接发送给目标用户,对方点击后即可加入,示例指令:
@bot.command() async def invite_to_guild(ctx, user: discord.User): invite = await ctx.guild.create_invite(max_age=0, max_uses=1) await user.send(f"邀请你加入服务器:{invite.url}") await ctx.send("邀请已发送至对方私信")
2. 退出当前群聊
2.1 退出群DM
@bot.command() async def leave_group(ctx): if isinstance(ctx.channel, discord.GroupChannel): await ctx.channel.leave() else: await ctx.send("当前不是群DM场景")
2.2 退出普通服务器
@bot.command() async def leave_guild(ctx): if ctx.guild: await ctx.guild.leave() else: await ctx.send("当前不在服务器场景")
3. 获取群聊ID
- 代码层面获取:只要拿到对应群聊对象(群DM为
GroupChannel对象,普通服务器为Guild对象),直接读取.id属性即可:# 获取当前群DM ID group_id = ctx.channel.id # 获取当前普通服务器ID guild_id = ctx.guild.id - 客户端手动获取:开启Discord客户端的开发者模式(设置->高级->开发者模式),右键点击群聊/服务器,选择「复制ID」即可。
4. 修改群聊名称与头像
4.1 修改群DM名称和头像
@bot.command() async def edit_group(ctx, new_name: str = None): if not isinstance(ctx.channel, discord.GroupChannel): await ctx.send("仅可在群DM中使用该指令") return edit_kwargs = {} if new_name: edit_kwargs["name"] = new_name # 如需修改头像,添加参数:edit_kwargs["icon"] = await discord.File("本地头像路径.png").read() try: await ctx.channel.edit(**edit_kwargs) await ctx.send("群聊信息修改成功") except Exception as e: await ctx.send(f"修改失败:{str(e)}")
4.2 修改普通服务器名称和头像
@bot.command() async def edit_guild(ctx, new_name: str = None): if not ctx.guild: await ctx.send("仅可在服务器中使用该指令") return edit_kwargs = {} if new_name: edit_kwargs["name"] = new_name # 如需修改头像,添加参数:edit_kwargs["icon"] = await discord.File("本地头像路径.png").read() try: await ctx.guild.edit(**edit_kwargs) await ctx.send("服务器信息修改成功") except Exception as e: await ctx.send(f"修改失败:{str(e)}")
内容的提问来源于stack exchange,提问作者6Ex
相关产品推荐
相关产品推荐

