You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何检测鼠标移动并实现Discord Bot状态定时自动切换

实现基于鼠标移动状态的Discord机器人状态更新

步骤1:安装依赖

首先需要安装用于检测鼠标位置的pynput库:

pip install pynput

步骤2:完整代码实现

import discord
from discord.ext import tasks
from pynput.mouse import Controller

# 初始化Discord客户端,按需配置权限
intents = discord.Intents.default()
client = discord.Client(intents=intents)

# 初始化鼠标控制器与上次位置记录
mouse = Controller()
last_mouse_pos = None

@tasks.loop(seconds=1)
async def change_status():
    global last_mouse_pos
    current_pos = mouse.position
    
    if current_pos != last_mouse_pos:
        # 鼠标移动时,设置忙碌状态
        await client.change_presence(
            status=discord.Status.dnd,
            activity=discord.Game(name="Up")
        )
        last_mouse_pos = current_pos
    else:
        # 鼠标未移动时,设置空闲状态
        await client.change_presence(
            status=discord.Status.idle,
            activity=discord.Game(name="Inactive")
        )

@client.event
async def on_ready():
    print(f'Logged in as {client.user}')
    # 启动状态更新定时任务
    change_status.start()

# 替换为你的机器人令牌
client.run('YOUR_BOT_TOKEN')

代码说明

  • 鼠标检测逻辑:通过pynput的鼠标控制器获取当前坐标,与上次记录的坐标对比,判断是否发生移动。首次运行时因无历史坐标,会默认判定为鼠标移动并设置忙碌状态。
  • 状态更新规则:每隔1秒执行一次状态检查,根据鼠标移动情况切换机器人的在线状态和活动展示文本。
  • 环境适配:pynput支持Windows、macOS、Linux多平台,Linux系统可能需额外安装libxtst-dev类依赖包保证正常运行。

内容的提问来源于stack exchange,提问作者Yugii

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.15 01:45:08