如何通过IRC机器人进行投票?

4 投票
1 回答
1356 浏览
提问于 2025-04-16 14:35

我用socket搭建了一个IRC机器人,添加了一些命令,但我想加一个“投票”的功能。理想情况下,机器人会接收到这样的命令格式:

!poll <名字> <选项1> <选项2> <选项3> <时间>

我该怎么做才能检查投票的用户,并在一定时间后结束投票呢?

提前谢谢大家,

一个绝望的Python初学者。

补充:非常感谢大家的回复,我决定使用全局变量(我知道,我知道),因为我不知道还有其他方法。再次非常感谢!

1 个回答

1

好吧,我感觉我的Python有点生疏了,不过我想我可以回答这个问题——虽然可能不是最好的答案。

如果你打算同时进行很多投票,你可以用一个字典来存放多个自定义类的实例,比如Poll(投票)。这里有一个可能的解决方案:

class PollVotes(object):
    def __init__(self):
        self.votes = []
        self.stoptime = "some date/time" #I can't remember how to do this bit ;)

    def add_vote(self, vote_value): 
        self.votes.append(vote_value);

    def tally_votes(self):
        return self.votes.size()

    def has_closed(self):
        if time_now >= self.stoptime: # I forget how you'd do this exactly, but it's for sake of example
            return True
        else:
            return False

#then use it something like this
poll_list = {}
#irc processing...
if got_vote_command:
    if poll_list["channel_or_poll_name"].has_ended(): 
        send("You can no longer vote.")
    else:
        poll_list["channel_or_poll_name"].add_vote(persons_vote)
        #send the tally
        send("%d people have now voted!" % poll_list["channel_or_poll_name"].tally_votes())

当然,你需要根据自己的需求来修改投票类,比如允许在一次投票中选择多个选项,记录谁投了什么(如果你想要这个功能),等等。

至于如何检查投票是否结束,你可以在投票类中添加一个结束时间,并写一个函数来判断这个时间是否已经过去,返回真或假。你可能还需要看看datetime模块的文档……

总之,希望这能帮到你。

撰写回答