简体   繁体   English

如何保持python 3脚本(Bot)运行

[英]How to keep a python 3 script (Bot) running

(Not native English, sorry for probably broken English. I'm also a newbie at programming). (不是母语英语,对不起可能是英语不好。我也是编程的新手)。
Hello, I'm trying to connect to a TeamSpeak server using the QueryServer to make a bot. 您好,我正在尝试使用QueryServer连接到TeamSpeak服务器来制作机器人。 After days of struggling with it... it works, with only 1 problem, and I'm stuck with that one. 经过几天的挣扎......它有效,只有一个问题,我坚持使用那一个。

If you need to check, this is the TeamSpeak API that I'm using: http://py-ts3.readthedocs.org/en/latest/api/query.html 如果您需要检查,这是我正在使用的TeamSpeak API: http//py-ts3.readthedocs.org/en/latest/api/query.html

And this is the summary of what actually happens in my script: 这是我的脚本中实际发生的事情的摘要:

  1. It connects. 它连接起来。
  2. It checks for channel ID (and it's own client ID) 它检查通道ID(以及它自己的客户端ID)
  3. It joins the channel 它加入了频道
  4. Script ends so it disconnects. 脚本结束,因此断开连接。

My question is: How can I make it doesn't disconnects? 我的问题是:如何让它不断开? How can I make the script stay in a "waiting" state so it can read if someone types "hi bot" in the channel? 如何让脚本保持“等待”状态,以便在有人在频道中键入“hi bot”时它可以读取? All the code needed to read texts and answer to them seems easy to program, however I'm facing a problem where I can't keep the bot "running" since it closes the file as soon as it ends running the script. 阅读文本和回答它们所需的所有代码似乎都很容易编程,但是我遇到了一个问题,我无法让机器人“运行”,因为它一旦结束运行脚本就会关闭文件。

More info: 更多信息:
I am using Python 3.4.1 . 我使用的是Python 3.4.1
I tried learning Threading http://www.tutorialspoint.com/python/python_multithreading.htm but either M'm dumb or it doesn't work the way I though it would. 我试过学习Threading http://www.tutorialspoint.com/python/python_multithreading.htm,但要么是哑巴,要么它不会像我那样工作。
In the API there's a function named on_event that I would like to keep running all the time. 在API中有一个名为on_event的函数,我希望它一直在运行。 The bot code should only be run once and then stay "waiting" until an event happens. 机器人代码应该只运行一次然后保持“等待”直到事件发生。 How should i do that? 我该怎么做? No clue. 没有线索。

Code: 码:

import ts3
import telnetlib
import time

class BotPrincipal:
    def Conectar(ts3conn):
        MiID = [i["client_id"] for i in ts3conn.whoami()]
        ChannelToJoin = "[Pruebas] Bots"
        ts3conn.on_event = BotPrincipal.EventHappened()
        try: 
            BuscandoIDCanal = ts3conn.channelfind(pattern=ChannelToJoin) 
            IDCanal = [i["cid"] for i in BuscandoIDCanal]
            if not IDCanal: 
                print("No channel found with that name")
                return None
            else:
                MiID = str(MiID).replace("'", "")
                MiID = str(MiID).replace("]", "")
                MiID = str(MiID).replace("[", "")
                IDCanal = str(IDCanal).replace("'", "")
                IDCanal = str(IDCanal).replace("]", "")
                IDCanal = str(IDCanal).replace("[", "")                
                print("ID de canal " + ChannelToJoin + ": " + IDCanal)
                print("ID de cliente " + Nickname + ": " + MiID)
            try:
                print("Moving you into: " + ChannelToJoin)
                ts3conn.clientmove(cid=IDCanal, clid=MiID) #entra al canal
                try:
                    print("Asking for notifications from: " + ChannelToJoin)
                    ts3conn.servernotifyregister(event="channel", id_=IDCanal)
                    ts3conn.servernotifyregister(event="textchannel", id_=IDCanal)
                except ts3.query.TS3QueryError:
                    print("You have no permission to use the telnet command: servernotifyregister")
                print("------- Bot Listo -------")
            except ts3.query.TS3QueryError:
                print("You have no permission to use the telnet command: clientmove")
        except ts3.query.TS3QueryError:
            print("Error finding ID for " + ChannelToJoin + ". telnet: channelfind")

    def EventHappened():
        print("Doesn't work")

# Data needed #
USER = "thisisafakename"
PASS = "something"
HOST = "111.111.111.111"
PORT = 10011
SID = 1

if __name__ == "__main__":    
    with ts3.query.TS3Connection(HOST, PORT) as ts3conn:
        ts3conn.login(client_login_name=USER, client_login_password=PASS)
        ts3conn.use(sid=SID)
        print("Connected to "+HOST)
        BotPrincipal.Conectar(ts3conn)

From a quick glimpse at the API, it looks like you need to explicitly tell the ts3conn object to wait for events. 从API的快速浏览看,您需要明确告诉ts3conn对象等待事件。 There seem to be a few ways to do it, but ts3conn.recv(True) seems like the most obvious: 似乎有几种方法可以做到,但ts3conn.recv(True)似乎最明显:

Blocks untill all unfetched responses have been received or forever, if recv_forever is true. 如果recv_forever为真,则直到收到所有未获取的响应或永久收到块。

Presumably as each command comes in, it will call your on_event handler, then when you return from that it will go back to waiting forever for the next command. 据推测,当每个命令进入时,它将调用你的on_event处理程序,然后当你从那里返回时它将返回到永远等待下一个命令。

I don't know if you need threads here or not, but the docs for recv_in_thread make it sound like you might: 我不知道你是否需要线程,但recv_in_thread的文档听起来像你可能:

Calls recv() in a thread. 在线程中调用recv() This is useful, if you used servernotifyregister and you expect to receive events. 如果您使用servernotifyregister并且您希望接收事件,这很有用。

You presumably want to get both servernotify events and also commands, and I guess the way this library is written you need threads for that? 你可能想要获得servernotify事件和命令,我想这个库的编写方式你需要线程吗? If so, just call ts3conn.recv_in_thread() instead of ts3conn.recv(True) . 如果是这样,只需调用ts3conn.recv_in_thread()而不是ts3conn.recv(True) (If you look at the source , all that does is start a background thread and call self.recv(True) on that thread.) (如果查看源代码 ,那么所有操作都是启动后台线程并在该线程上调用self.recv(True) 。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM