【问题标题】:Python Twitch bot !addcom difficultiesPython Twitch 机器人!addcom 困难
【发布时间】:2015-05-30 19:59:34
【问题描述】:

我正在使用 Python 制作 Twitch 机器人,因为 mIRC 开始要求我付款,所以我选择了更简单且免费的东西!我当前的问题是我想创建一个命令 (!addcom),版主可以在其中添加其他用户可以使用的命令。

例如,!addcom !test This is a test 会将!test This is a test 写入文件或Python 文件本身,然后有人可以执行!test,它会在聊天中说This is a test。目前我正在努力寻找一种好的方法来做到这一点,这就是我目前所拥有的:

def command_addcom():
    file = open("test.txt", "w")
    msg = input('')
    file.write(msg)
    file.close()
    send_message(CHAN,'Command added (testing)')

不幸的是,这只要求在命令提示符下输入,根本没有帮助。我希望它直接从聊天中获取文本并将其放入文件中。抱歉,我没有太多代码要显示,但这就是整个命令!提前感谢您的帮助。

【问题讨论】:

标签: python twitch


【解决方案1】:

我建议您将所有用户定义的命令保存在 python 字典中。例如,在您的示例中,将是

command['!test'] = 'This is a test'

对于你提到的保存问题,我建议使用json 模块。 保存上面的 command dict

with file('setting.json','w') as settingFile
    json.dump(command, settingFile)

每次机器人初始化时,都应该从实际的 json 文件中加载 command dict

with file('setting.json','r') as settingFile:
    command = json.load(settingFile)

所以你现在在程序中有用户定义的命令字典


最后,在您的用户消息解析器中(这里我假设它是userMessage),您应该检查是否可以在 command 字典中找到用户命令。试试

userCommand = userMessage.split(' ')[0]
if command[userCommand]:
    # sendmsg to Twicth IRC
    print command[userCommand]

官方 python 文档应该提供了有关如何使用json 模块的足够信息,或者您也可以尝试ConfigParser

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-05-03
    • 2017-12-26
    • 2018-12-31
    • 2021-02-19
    • 1970-01-01
    • 1970-01-01
    • 2019-05-08
    • 2021-05-20
    相关资源
    最近更新 更多