botpy

repository·master·Indexed 21 days ago

https://github.com/tencent-connect/botpy

A Python framework for developing QQ bots based on the Robot Open Platform API. It provides an event-driven interface for handling messages, group interactions, and rich media. The library requires Python 3.8 or higher and is installed via the qq-botpy package.

Tokens
6.7K
Snippets
28
Records
31
Agent score
75%

What's inside botpy

  1. Explore botpy example capabilities

    master

    The examples/ directory contains various scripts demonstrating different bot functionalities. Key capabilities include:

    • Messaging & Replies: Passive replies to @mentions (async, markdown, embed, keyboard, file/image), private messages (DMS), group text/media replies, and C2C (friend) replies.
    • Command Handling: Using the Command decorator for @mention replies.
    • Event Handling: Guild member changes, group management events, C2C management events, audio/live channel member events, and open forum events.
    • Bot Actions: Sending announcements, pinning messages, recalling (deleting) messages, and managing schedules.
    • Data & Permissions: Querying API permissions, getting reaction user lists, and interacting with various message types.
  2. How botpy works: Client, Intents, and Events

    master

    To build a bot with botpy, you follow a three-step pattern:

    1. Inherit from bot.Client: Create a custom class that inherits from botpy.Client to define your bot's logic.
    2. Implement Event Handlers: Define asynchronous methods within your class to handle specific events (e.g., on_at_message_create). Each event handler receives a specific data object (e.g., botpy.message.Message for message events).
    3. Configure Intents and Run: Initialize botpy.Intents to specify which event channels your bot should listen to, then instantiate your client and call .run() with your appid and secret.

    Note: Authentication in newer versions (v1.1.5+) requires both appid and secret (AppSecret).

    import botpy
    from botpy.message import Message
    
    # 1. Inherit from botpy.Client
    class MyClient(botpy.Client):
        # 2. Implement event handlers
        async def on_at_message_create(self, message: Message):
            await message.reply(content=f"Bot {self.robot.name} received your @message: {message.content}")
    
    # 3. Set intents and run
    intents = botpy.Intents(public_guild_messages=True) 
    client = MyClient(intents=intents)
    client.run(appid="12345", secret="xxxx")
  3. Quickstart: Create a basic bot client

    master

    To build a bot, follow these three steps:

    1. Inherit from botpy.Client: Create your own client class.
    2. Implement event handlers: Override methods like on_ready or on_at_message_create to handle specific bot events. Note that event handlers receive specific data objects (e.g., Message for message events).
    3. Configure Intents and Run: Define which events the bot should listen to using botpy.Intents, instantiate your client, and call .run() with your appid and token.
    import botpy
    from botpy.types.message import Message
    
    class MyClient(botpy.Client):
        async def on_ready(self):
            print(f"robot 「{self.robot.name}」 on_ready!")
    
        async def on_at_message_create(self, message: Message):
            # Automatically reply when @mentioned
            await message.reply(content=f"机器人{self.robot.name}收到你的@消息了: {message.content}")
    
    # Set up intents to listen for public guild messages
    intents = botpy.Intents(public_guild_messages=True)
    client = MyClient(intents=intents)
    
    # Start the client
    client.run(appid="12345", token="xxxx")
  4. Listen to Public Guild Message Events

    master

    To listen for messages in public channels (e.g., when a bot is @mentioned or a message is deleted), you must subscribe to the public_guild_messages intent.

    Required imports:

    • botpy.Intents
    • botpy.message.Message
    import botpy
    from botpy.message import Message
    
    intents = botpy.Intents(public_guild_messages=True)
    
    class MyClient(botpy.Client):
        async def on_at_message_create(self, message: Message):
            # Triggered when the bot is @mentioned
            pass
    
        async def on_public_message_delete(self, message: Message):
            # Triggered when a channel message is deleted
            pass
  5. Listen to Guild Member Events

    master

    To monitor members joining, leaving, or updating their profiles in a guild, subscribe to the guild_members intent.

    Required imports:

    • botpy.Intents
    • botpy.user.Member
    import botpy
    from botpy.user import Member
    
    intents = botpy.Intents(guild_members=True)
    
    class MyClient(botpy.Client):
        async def on_guild_member_add(self, member: Member):
            pass
        async def on_guild_member_update(self, member: Member):
            pass
        async def on_guild_member_remove(self, member: Member):
            pass
  6. Listen to Direct Message (DM) Events

    master

    To listen to private messages sent directly to the bot, subscribe to the direct_message intent.

    Required imports:

    • botpy.Intents
    • botpy.message.DirectMessage
    import botpy
    from botpy.message import DirectMessage
    
    intents = botpy.Intents(direct_message=True)
    
    class MyClient(botpy.Client):
        async def on_direct_message_create(self, message: DirectMessage):
            # Triggered when receiving a DM
            pass
    
        async def on_direct_message_delete(self, message: DirectMessage):
            # Triggered when a DM is deleted or retracted
            pass
  7. Listen to Audio Events

    master

    To monitor audio playback and microphone status, subscribe to the audio_action intent.

    Required imports:

    • botpy.Intents
    • botpy.audio.Audio
    import botpy
    from botpy.audio import Audio
    
    intents = botpy.Intents(audio_action=True)
    
    class MyClient(botpy.Client):
        async def on_audio_start(self, audio: Audio):
            pass
        async def on_audio_finish(self, audio: Audio):
            pass
        async def on_audio_on_mic(self, audio: Audio):
            pass
        async def on_audio_off_mic(self, audio: Audio):
            pass
  8. Subscribe to events using Intents

    master

    To receive specific events, you must configure botpy.Intents when initializing your client. There are two primary ways to define intents: passing them directly to the constructor or modifying an existing Intents object.

    Method 1: Direct Initialization

    Pass the desired intent flags directly into the botpy.Intents() constructor.

    Method 2: Incremental Configuration

    Initialize with botpy.Intents.none() and then set specific attributes to True.

    Shortcut Methods

    • botpy.Intents.all(): Subscribes to all available events.
    • botpy.Intents.default(): Subscribes to all default public events.
    # Method 1: Direct
    intents = botpy.Intents(public_guild_messages=True, direct_message=True, guilds=True)
    client = MyClient(intents=intents)
    
    # Method 2: Incremental
    intents = botpy.Intents.none()
    intents.public_guild_messages = True
    intents.direct_message = True
    intents.guilds = True
    
    # Shortcuts
    intents = botpy.Intents.all()
    intents = botpy.Intents.default()
  9. Listen to Forum Events

    master

    To monitor forum activity (threads, posts, replies, and audit results), subscribe to the forums intent.

    Note: This intent is only available for Private (私域) bots.

    Required imports:

    • botpy.Intents
    • botpy.forum.Thread
    • botpy.types.forum.Post, Reply, AuditResult
    import botpy
    from botpy.forum import Thread
    from botpy.types.forum import Post, Reply, AuditResult
    
    # Note: Only Private bots can set this intent
    intents = botpy.Intents(forums=True)
    
    class MyClient(botpy.Client):
        async def on_forum_thread_create(self, thread: Thread):
            pass
        async def on_forum_thread_update(self, thread: Thread):
            pass
        async def on_forum_thread_delete(self, thread: Thread):
            pass
        async def on_forum_post_create(self, post: Post):
            pass
        async def on_forum_post_delete(self, post: Post):
            pass
        async def on_forum_reply_create(self, reply: Reply):
            pass
        async def on_forum_reply_delete(self, reply: Reply):
            pass
        async def on_forum_publish_audit_result(self, auditresult: AuditResult):
            pass
  10. Listen to Message Audit Events

    master

    To monitor the results of message content audits (pass/reject), subscribe to the message_audit intent.

    Required imports:

    • botpy.Intents
    • botpy.message.MessageAudit
    import botpy
    from botpy.message import MessageAudit
    
    intents = botpy.Intents(message_audit=True)
    
    class MyClient(botpy.Client):
        async def on_message_audit_pass(self, message: MessageAudit):
            pass
        async def on_message_audit_reject(self, message: MessageAudit):
            pass