关于一个PythonWebsocket聊天Bot的代码问题【萌新零基础】【勿喷】
  • 板块学术版
  • 楼主_DeadPig_
  • 当前回复6
  • 已保存回复6
  • 发布时间2023/8/2 13:11
  • 上次更新2023/11/3 06:22:58
查看原帖
关于一个PythonWebsocket聊天Bot的代码问题【萌新零基础】【勿喷】
724981
_DeadPig_楼主2023/8/2 13:11

目前的问题就是当

if cg == 1 and clt == 1:
   if content == '`join`':
      player.put(sender)
      score.put(0)
   if cg ==1 and sender == nowpl and tov == 0 and content in anslis:
      plwd = content

没有被删除时,后面的判断都不会执行,我怀疑是,变量初始化的问题,但是并没有找到原因,有没有P党大佬教一教

完整代码:

import websocket
import json
from queue import Queue
import time
import datetime
import threading
import random

nick = "Evarate"
channel = "123456"
Mpass = "123456"

cg = 0
clt = 0
nowpl = ''
plwd = ''
color = ["#FF0033", "#ff66cc", "#ccff00", "#ffff33","#66ffff","#3333ff","#ff9900","#ffffff","#000000","#FFCC66"]
anslis = ["红色","粉红","绿色","黄色","天蓝","深蓝","橙色","白色","黑色","烫金色"]

his=Queue()
player=Queue()
score = Queue()

def on_open(ws):
    print("Trying to connect")

    # 发送加入频道的请求
    join = {'cmd': 'join','nick': nick,'password': Mpass ,'channel': channel}
    ws.send(json.dumps(join))
    if ws.sock.connected:
        print("Connected")  # 连接成功的提示信息
    else:
        print("Connection failed")  # 连接失败的提示信息

def on_message(ws, message):
    data = json.loads(message)
    if 'cmd' in data and data['cmd'] == 'chat':
        content = data['text']
        sender = data['nick']
        trip = data['trip']
        nowtime = datetime.datetime.now()
        if trip != "T6mzFH":        #自我过滤 
            his.put(f"{nowtime} {sender}#{trip} : {content}")
            print("Saved Meassage")
            print(f"Message form {sender}#{trip} :{content}")
            if cg == 1 and clt == 1:
                if content == '`join`':
                    player.put(sender)
                    score.put(0)
            if cg ==1 and sender == nowpl and tov == 0 and content in anslis:
                plwd = content

             对收到的消息进行回应
            if content == './history' :
                size = his.qsize()
                rests = ''
                for i in range(size):
                    tmp = his.get()
                    rests = rests + '\n' + tmp
                    his.put(tmp)

                response = {'cmd': 'chat','text': rests , 'channel': channel}  
                ws.send(json.dumps(response))
                print(cg)
            if content == './colorgame' and cg == 0:
                cg = 1
                clt = 1
                while not player.empty():player.get()
                while not score.empty(): score.get()
                response = {'cmd': 'chat','text': '输入`join`加入游戏(包括Markdown)' , 'channel': channel}  
                ws.send(json.dumps(response))
                response = {'cmd': 'chat','text': '25秒后结束报名' , 'channel': channel}  
                ws.send(json.dumps(response))
                threading.Thread(target=cgame).start()
            elif content == './colorgame' and cg == 1:
                fuckyouresponse = {'cmd': 'whisper','nick' : sender ,'text': '游戏是现在进行时哦' }  
                ws.send(json.dumps(fuckyouresponse))

            if content == '`join`' and clt == 1:
                player.put(sender)
                print("Saved Player")
            if cg == 1 and sender == nowpl and tov == 0:
                plwd = content

        if his.qsize() > 150 : his.get()

def cgame():
    print('cgame start\n')
    time.sleep(25)
    print('join end')
    clt = 0
    size = player.qsize()
    resforpl = 'Player: '

    for i in range(size):
        i = player.get()
        resforpl = resforpl + i + ' '
        player.put(i)
        score.put(0)

    if size == 0:
        ws.send(json.dumps({'cmd': 'chat','text': '无人报名...' , 'channel' : channel}))
        return
    ws.send(json.dumps({'cmd': 'chat','text': f'{resforpl}\n 游戏现在开始:' , 'channel' : channel}))
    threading.Thread(target=cgtimer,args=(300,)).start()

    while cg == 1:
        plwd = ''
        flag = 0

        nowpl=player.get()
        nowsc=score.get()
        player.put(nowpl)
        ws.send(json.dumps({'cmd': 'chat','text': (nowpl + f'!你的回合,猜猜我说`{nowpl}最帅`的时候是什么颜色?(格式:<颜色>)')  , 'channel' : channel}))
        ws.send(json.dumps({'cmd': 'chat','text': '可猜颜色:红色、粉红、绿色、黄色、天蓝、深蓝、橙色、白色、黑色、烫金色,示例:红色'  , 'channel' : channel}))
        tov=0
        threading.Thread(target=timer,args=(15,)).start()
        while tov == 0:
            if plwd != '':
                flag = 1
                break
        if not flag:
            ws.send(json.dumps({'cmd': 'chat','text': '太慢了,0昏!' , 'channel' : channel}))
            score.put(0)
        else:
            colornum = random.randint(0,9)
            ws.send(json.dumps({'cmd': 'changecolor', 'color' : f'{color[colornum]}'}))

            if anslis[colornum] == plwd:
                ws.send(json.dumps({'cmd': 'chat','text': f'`{nowpl}猜对了,2昏`' , 'channel' : channel}))
                score.put(nowsc+2)
            else:
                ws.send(json.dumps({'cmd': 'chat','text': f'`{nowpl}猜错了,1昏`' , 'channel' : channel}))
                score.put(nowsc+1)

def timer(x):
    time.sleep(x)
    tov = 1

def cgtimer(x):
    time.sleep(x)
    cg = 0

ws = websocket.WebSocketApp("wss://hack.chat/chat-ws/",
                            on_open=on_open,
                            on_message=on_message)
cg = 0
clt = 0
ws.run_forever()

2023/8/2 13:11
加载中...