【问题标题】:Modular coding in a python botpython 机器人中的模块化编码
【发布时间】:2017-11-25 01:18:58
【问题描述】:

我是 stackoverflow(和编码)的新手。我想知道是否在电报机器人中,使用 python,我将如何进行模块化编码。我的意思是每个命令都在不同的文件中。如果我有一个小型机器人通过 echo 回复消息,我只需要一个 run.py 文件。但是我的机器人有几个模块,比如moderationfun games 等。所以我想创建一个类可能会更好?或者可能只是将每个命令作为一个函数放在几个不同的文件中,例如moderation/automod.py,moderation/muteuser.py,因为这些命令中的每一个在将来都可能占用大量空间。但是,如果我导入整个文件夹以及多个文件夹,我将导入 LOT 的文件。我的问题是:如何在不导入 2000 个文件的情况下正确管理不同的命令?

如果有帮助,我使用 python-telegram-bot 包装器。

谢谢你:-)

【问题讨论】:

  • 您能举例说明这些命令的含义吗?您是否考虑过使用 yml 或 json 格式的声明性选项?
  • 我所说的命令的意思是,像这样的:
  • automod.py - 用于自动删除垃圾邮件 help.py - 显示帮助消息 ``` def help(bot, update): bot.send_message("Use /start to use the bot") ` ``
  • :(我这里没有答案

标签: python bots telegram python-telegram-bot


【解决方案1】:

所以命令本身是:“使用 /start 来使用机器人”?如果您使用相同的方法重复多个命令,我会创建一个 json 或 yml 文件。例如在 json 中:

commands.json

{
  "send_message": 
    {
      "help":"Use /start to use the bot",
       "anotherCommand":"This is another command"
    },
  "method_to_do_other_stuff": {
       "command":"The command value"
  }
}

用json python模块导入

import json
import bot
commands = {}
with open("commands.json") as f:
   commands = json.load(f)
#Call the method
getattr(bot, commands['send_message'])(commands['send_message']['help'])

这显然可以改进以使其更清洁和更简单。由于我没有库,因此尚未经过测试,请修复机器人导入以正确导入您需要的内容。

-----------------------修订版 ------------ -------------------

多个导入的示例代码。 根据类别创建一个文件夹以包含您的命令或多个命令 - 本示例的命令文件夹。

__init__.py 每个文件夹内容中的文件对于此示例,有一个用于 commands 文件夹:

from os.path import dirname, basename, isfile
import glob
modules = glob.glob(dirname(__file__)+"/*.py")
__all__ = [ basename(f)[:-3] for f in modules if isfile(f) and not f.endswith('__init__.py')]

例如 bot bot.py 的文件:

from commands import *
if __name__ == "__main__":
    print apple.command()
    print orange.command()

apple.py在命令文件夹中

def command():
    return "apple"

orange.py 在命令文件夹中

def command():
    return "orange"

文件和文件夹的结构

bot.py
commands/
    apple.py
    orange.py
    __init__.py

【讨论】:

  • 实际上,通过命令我的意思是回复$google something 之类的东西,所以它实际上是一个机器人和一个服务器。我需要在这里编写逻辑,例如向 google 发出请求,然后将其作为消息发送。像这样我还有很多其他的问题,比如有人在服务器上说$pingtest。我不知道将所有这些逻辑作为不同的文件放在哪里。
  • 这是一个示例机器人github.com/karthikeyankc/ottis,在文件ottis.py 中,您可以看到机器人的逻辑。但是如果我有太多的逻辑,我需要很多文件。我的意思是把get_wiki_summary 放在一个单独的文件中。但仍然没有进行 1000 次导入,因为对于更大的机器人来说,会有很多逻辑存在
  • 所以您的问题不在于命令本身,而在于导入包含每个处理程序的多个文件对吗?如果是这样,我会修改我的答案
  • @llhicas 没错!
  • 检查修改后的答案是否是你要找的
猜你喜欢
  • 1970-01-01
  • 2018-01-29
  • 1970-01-01
  • 2019-08-11
  • 2012-01-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多