-1

我将从文件或其他东西生成正则表达式,并在 @re_botcmd 中需要它

但我收到错误:“未定义”有没有办法定义 re_botcmd 正在查找的变量?

from errbot import BotPlugin, re_botcmd
from pathlib import Path
import re

class ModHelper(BotPlugin):
 """Help Mods Warning User and kick/ban them"""

 def activate(self):
     self.my_file = Path("./filter.txt")
     if not self.my_file.is_file():
         return

     self.filter = open('filter.txt', 'r')
     for self.tmp in self.filter:
         if not self['reg']:
             self['reg'] = '(',self.tmp,')'
         else:
             self['reg'] = self['reg'],'|(',self.tmp,')'

     return super().activate()


 @re_botcmd(pattern=self['reg'], prefixed=False, flags=re.IGNORECASE)
 def test_warn(self, msg, match):
      """Test"""
      return "Warn User"

来自日志文件的错误:

Errbot‎: File "<frozen importlib._bootstrap_external>", line 678, in exec_module
File "<frozen importlib._bootstrap>", line 205, in _call_with_frames_removed
File "/home/errbot/errbot-root/plugins/err-modhelper/modhelper.py", line 5, in <module>
class ModHelper(BotPlugin):
File "/home/errbot/errbot-root/plugins/err-modhelper/modhelper.py", line 23, in ModHelper
@re_botcmd(pattern=self['reg'], prefixed=False, flags=re.IGNORECASE)
NameError: name 'self' is not defined

谢谢~

4

2 回答 2

0

尝试这样的事情:

class ModHelper(BotPlugin):
 """Help Mods Warning User and kick/ban them"""
 def __init__(self, reg=None):
    self.reg = reg

 def activate(self):
     self.my_file = Path("./filter.txt")
     if not self.my_file.is_file():
         return

     self.filter = open('filter.txt', 'r')
     for self.tmp in self.filter:
         if not self.reg:
             self.reg = '(',self.tmp,')'
         else:
             self.reg = self.reg,'|(',self.tmp,')'

     return super().activate()


 @re_botcmd(pattern=self.reg, prefixed=False, flags=re.IGNORECASE)
 def test_warn(self, msg, match):
      """Test"""
      return "Warn User"
于 2017-07-05T09:01:00.507 回答
0

在聊天中识别提到 Jira 问题时,我遇到了类似的问题;识别器需要知道 Jira 项目的列表。我通过在一个小型实用程序类中在编译时获取该列表然后让识别器在运行时获取该列表来解决它:

class JiraProjects(object):

    def __init__(self):
        jira = Jira()
        self.list = jira.active_projects()
        self.recognizer = r'\b(?P<issue>(?:%s)-\d+)\b' % '|'.join(self.list)

projects = JiraProjects()

class JiraPlugin(BotPlugin):

    def activate(self):
        self.jira = Jira()
        super().activate()

@re_botcmd(prefixed=False, pattern=projects.recognizer, flags=re.IGNORECASE, matchall=True)
    def jira_recognize(self, msg, matches):
        """
        Provides information about any jira issue that is mentioned
        """
        for match in matches:
            issue = self.jira.get_issue(match.group(0))
            yield self.show_issue(issue)
于 2017-12-12T22:59:11.217 回答