How to get filepath from droped file with pyqt5? - drag-and-drop

I want to get path of the file dropped on QLabel. So I code like this, but label doesn't accept the file. What is the problem..?
Here is my code. So long code sorry and thank you!
import random
import sys
import pygame
import time
from PyQt5.QtGui import QPixmap
from PyQt5.QtCore import Qt, QTimer
from PyQt5.QtWidgets import QWidget, QLabel, QApplication, QDesktopWidget
class Example(QWidget):
size=100
imgNum=0
frameCount=4
isXmin = False
isXmax = False
isYmin = False
isYmax = False
isLeft= True
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
sizeObject = QDesktopWidget().screenGeometry()
# print(" Screen size : " + str(sizeObject.height()) + "x" + str(sizeObject.width()))
self.xMax=sizeObject.width()-10
self.yMax=sizeObject.height()-10
print(self.xMax)
print(self.yMax)
self.setWindowFlags(Qt.FramelessWindowHint)
self.setAttribute(Qt.WA_TranslucentBackground)
self.setStyleSheet("background-color:transparent;")
self.setGeometry(100, 100, 100, 100)
self.setWindowFlags(Qt.SplashScreen | Qt.WindowStaysOnTopHint)
self.setAcceptDrops(True)
self.label=QLabel(self)
self.label.setAcceptDrops(True)
self.pixmaps=[QPixmap('left.png'),QPixmap('stand.png'),QPixmap('right.png'),QPixmap('stand.png'),QPixmap('leftR.png'),QPixmap('standR.png'),QPixmap('rightR.png'),QPixmap('standR.png')]
for x in range(len(self.pixmaps)):
self.pixmaps[x]=self.pixmaps[x].scaled(self.size,self.size,Qt.KeepAspectRatio)
self.resize(self.pixmaps[2].width(),self.pixmaps[2].height())
self.label.setPixmap(self.pixmaps[len(self.pixmaps)-1])
self.changeTimer=QTimer(self)
self.changeTimer.timeout.connect(self.changeFoot)
self.moveTimer=QTimer(self)
self.moveTimer.timeout.connect(self.moving)
self.setAcceptDrops(True)
pygame.init()
pygame.mixer.music.load('hoi_imtemmie.mp3')
pygame.mixer.music.play()
self.show()
def dragEnterEvent(self, event):
if event.mimeData().hasUrls:
event.accept()
else:
event.ingore()
def dropEvent(self, event):
self.path=event.mimeData.urls()
def moving(self):
if self.distance == 0:
print(self.distance)
print(self.x(),"x",self.y())
self.label.setPixmap(self.pixmaps[1])
self.moveTimer.stop()
self.changeTimer.stop()
time.sleep(3)
self.setMovement()
return 0
else:
self.move(self.x()+self.direct[0],self.y()+self.direct[1])
self.distance-=1
if self.x()<=-10 :
self.distance=0
print("xm")
self.isXmin = True
if self.y()<=-10 :
self.distance=0
print("ym")
self.isYmin = True
if self.x()>=self.xMax:
self.distance=0
print("xM")
self.isXmax=True
if self.y()>=self.yMax :
self.distance=0
print("yM")
self.isYmax=True
def setMovement(self):
self.direct=[0,0]
while(self.direct[0]==0 and self.direct[1]==0):
self.direct=[random.randint(-1,1),random.randint(-1,1)]
if self.isXmax:
self.direct[0]=-1
if self.isXmin:
self.direct[0]=1
if self.isYmin:
self.direct[1]=1
if self.isYmax:
self.direct[1]=-1
if self.direct[0]== -1:
self.isLeft=True
self.imgNum=0
elif self.direct[0]== 1:
self.isLeft=False
self.imgNum=4
self.isXmax = False
self.isXmin = False
self.isYmin = False
self.isYmax = False
# if direct[0]*direct[1]==0 : self.delta = QPoint(dX*direct[0],dY*direct[1])
# else: self.delta=QPoint(direct[0]*(dX**(1/2)),direct[1]*(dY**1/2))
self.distance=random.randint(200,400)
self.changeTimer.start(300)
self.moveTimer.start(30)
def changeFoot(self):
self.label.setPixmap(self.pixmaps[self.imgNum])
if self.isLeft:
if self.imgNum<self.frameCount-1:
self.imgNum+=1
else :
self.imgNum=0
else:
if self.imgNum<2*self.frameCount-1:
self.imgNum+=1
else :
self.imgNum=self.frameCount
def mousePressEvent(self, QMouseEvent):
self.setMovement()
pygame.mixer.music.load('hoi_imtemmie.mp3')
pygame.mixer.music.play()
def keyPressEvent(self, QKeyEvent):
if QKeyEvent.key() == Qt.Key_Escape:
sys.exit()
# if QKeyEvent.key() == Qt.Key_G:
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
i set AcceptDrops(True)
self.setAcceptDrops(True)
and code about get filepath ▼
def dragEnterEvent(self, event):
if event.mimeData().hasUrls:
event.accept()
else:
event.ingore()
def dropEvent(self, event):
self.path=event.mimeData.urls()

Try to loop through event.mimeData().urls()
for url in event.mimeData().urls():
self.path = url.toLocalFile()

Related

Discord bot executes but doesn't function when testing in discord server

I've adjusted the main file and added a prefix "?" to my commands
import discord
from discord.ext import commands
import os
import asyncio
client = commands.Bot(command_prefix="?", intents = discord.Intents.all())
async def load():
for filename in os.listdir("./cogs"):
if filename.endswith(".py"):
await client.load_extension(f"cogs.{filename[:-3]}")
async def main():
async with client:
await load()
await client.start(TOKEN)
asyncio.run(main())
and added a simple ping command to test if the bot was working in discord. unfortunately all the commands except for ping does not work
import discord
from discord.ext import commands
from pymongo import MongoClient
bot_channel = BOTCHANNELID
talk_channels = [TALKCHANNELID]
level = ["test1", "test2", "test3"]
levelnum = [2,4,6]
cluster = MongoClient("MONGODBCODE")
levelling = cluster["NAME"]["NAME2"]
class levelsys(commands.Cog):
def __init__(self,client):
self.client = client
#commands.Cog.listener()
async def on_ready(self):
print("Ready!")
#commands.Cog.listener()
async def on_message(self, message):
if message.channel.id in talk_channels:
stats = levelling.find_one({"id" : message.author.id})
if not message.author.bot:
if stats is None:
newuser = {"id" : message.author.id, "xp" : 1}
levelling.insert_one(newuser)
else:
xp = stats["xp"] + 5
levelling.update_one({"id":message.author.id}, {"$set":{"xp":xp}})
lvl = 0
while True:
if xp < ((50*(lvl**2))+(50*(lvl-1))):
break
lvl += 1
xp -= ((50*((lvl-1)**2))+(50*(lvl-1)))
if xp == 0:
await message.channel.send(f"gz {message.author.mention} ! you lvled up to **level: {lvl}**")
for i in range(len(level)):
if lvl == levelnum[i]:
await message.author.add_roles(discord.utils.get(message.author.guild.roles, name=level[i]))
embed = discord.Embed(description=f"{message.author.mention} you have gotten role **{level[i]}**")
embed.set_thumbnail(url=message.author.avatar_url)
await message.channel.send(embed=embed)
#commands.command()
async def rank(self, ctx):
if ctx.channel.id == bot_channel:
stats = levelling.find_one({"id" : ctx.author.id})
if stats is None:
embed = discord.Embed(description="you haven't been studying lil bro")
await ctx.channel.send(embed=embed)
else:
xp = stats["xp"]
lvl = 0
rank = 0
while True:
if xp < ((50*(lvl**2))+(50*lvl)):
break
lvl += 1
xp -= ((50*((lvl-1)**2))+(50*(lvl-1)))
boxes = int((xp/(200*((1/2) * lvl)))*20)
rankings = levelling.find().sort("xp",-1)
for x in rankings:
rank += 1
if stats["id"] == x["id"]:
break
embed = discord.Embed(title="{}'s level stats".format(ctx.author.name))
embed.add_field(name="Name", value=ctx.author.mention, inline=True)
embed.add_field(name="XP", value=f"{xp}/{int(200*((1/2)*lvl))}", inline=True)
embed.add_field(name="Rank", value=f"{rank}/{ctx.guild.member_count}", inline=True)
embed.add_field(name="Progress Bar [lvl]", value=boxes * ":blue_square:" + (20-boxes) * ":white_large_squares:", inline = False)
embed.add_field(name='Level', value=f'{lvl}', inline=True)
embed.set_thumbnail(url=ctx.author.avatar_url)
await ctx.channel.send(embed=embed)
#commands.command()
async def dashboard(self, ctx):
if (ctx.channel.id == bot_channel):
rankings = levelling.find().sort("xp",-1)
i = 1
embed = discord.Embed(title="Rankings:")
for x in rankings:
try:
temp = ctx.guild.get_member(x["id"])
tempxp = x["xp"]
embed.add_field(name=f"{i}: {temp.name}", value=f"Total XP: {tempxp}", inline=False)
i += 1
except:
pass
if i == 11:
break
await ctx.channel.send(embed=embed)
#commands.command()
async def ping(self, ctx):
bot_latency = round(self.client.latency * 1000)
await ctx.send(f"Your ping is {bot_latency} ms !.")
async def setup(client):
await client.add_cog(levelsys(client))
I'm not too sure how I would go about fixing all the other commands to get them working. All help is much appreciated !

Why does kivy keep freezing when using python sockets?

I'm working on a basic client-server desktop app project using kivy & sockets & threading.
The client & server work on it's own, however when I try to integrate it with kivy, python & kivy don't want to respond & yet no definitive error pops up.
Could i have some ideas as to how to fix this?
This is the code that freezes when i run it, if i take away the import server_sock it works as a general gui and doesnt freeze.
import kivy
from kivy.app import App
from kivy.uix.label import Label
from kivy.uix.gridlayout import GridLayout
from kivy.uix.textinput import TextInput
from kivy.uix.button import Button
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.clock import Clock
import server_sock
import sys
kivy.require("2.1.0") #latest version
class ConnectPage(GridLayout):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.cols = 2
self.add_widget(Label(text="IP:"))
self.ip = TextInput(multiline=False)
self.add_widget(self.ip)
self.add_widget(Label(text="PORT:"))
self.port = TextInput(multiline=False)
self.add_widget(self.port)
self.add_widget(Label(text="USERNAME:"))
self.user = TextInput(multiline=False)
self.add_widget(self.user)
self.join = Button(text="Join")
self.join.bind(on_press=self.join_button)
self.add_widget(Label())
self.add_widget(self.join)
def join_button(self, instance):
port = self.port.text
ip = self.ip.text
user = self.user.text
info = f"Attempting to join {ip}:{port} as {user}"
chat_app.info_page.update_info(info)
chat_app.screen_manager.current = "Info"
Clock.shedule_once(self.connect,1)
def connect(self, _):
port = int(self.port.text)
ip = self.ip.text
user = self.user.text
try:
server_sock.connect(ip, port)
chat_app.create_chat_page()
chat_app.screen_manager.current = "Chat"
except:
show_error(message="not gonna happen")
class InfoPage(GridLayout):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.cols = 1
self.message = Label(halign="center", valign="middle", font_size="30")
self.message.bind(width=self.update_text_width)
self.add_widget(self.message)
def update_info(self,message):
self.message.text = message
def update_text_width(self, *_):
self.message.text_size = (self.message.width*0.9, None)
class ChatPage(GridLayout):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.cols = 1
self.add_widget(Label(text="Hey at least it works till now"))
class ChatApp(App):
def build(self):
self.screen_manager = ScreenManager()
self.connect_page = ConnectPage()
screen = Screen(name="Connect")
screen.add_widget(self.connect_page)
self.screen_manager.add_widget(screen)
self.info_page = InfoPage()
screen= Screen(name="Info")
screen.add_widget(self.info_page)
self.screen_manager.add_widget(screen)
return self.screen_manager
def create_chat_page(self):
self.chat_page = ChatPage()
screen = Screen(name="Chat")
screen.add_widget(self.chat_page)
self.screen_manager.add_widget(screen)
def show_error(message):
chat_app.info_page.update_info(message)
chat_app.screen_manager.current = "Info"
Clock.shedule_once(sys.exit, 10)
if __name__ == "__main__":
chat_app =ChatApp()
chat_app.run()
This is the server_sock file
import socket
import threading
import socket
HOST = '127.0.0.1'
PORT = 55555
server = socket.socket(
socket.AF_INET,
socket.SOCK_STREAM
)
try:
server.bind((HOST, PORT))
except:
print(f'unable to bind to {HOST} and {PORT}')
server.listen()
print(f"Listening for connections on {HOST}: {PORT}")
clients = []
nicknames = []
def broadcast(message):
for client in clients:
client.send(message)
def message_recv(client):
while True:
try:
message = client.recv(2048)
broadcast(message)
except:
index = clients.index(client)
clients.remove(client)
nickname = nicknames[index]
broadcast(f'{nickname} left the chat'.encode('ascii'))
nicknames.remove(nickname)
break
def recieve():
while True:
client, address = server.accept()
print(f"Connected with {str(address)}")
client.send("SOMETHING".encode('ascii'))
nickname = client.recv(2048).decode('ascii')
nicknames.append(nickname)
clients.append(client)
print(f"Nickname of the client is {nickname}")
broadcast(f"{nickname} joined the chat".encode('ascii'))
client.send("Connected to the server".encode('ascii'))
thread = threading.Thread(target=message_recv, args=(client,))
thread.start()
print("Server is listening")
recieve()

why none of the clients are getting a tray

I am working on a buffet simulation of a buffet. So basically the client will first go through the payment. Then he should go to get his tray which is the part that does not work. After, he should go get his food.
I dont understand why the Clients are not going to the tray queue.
In fact, right-now the client is paying and then he his going directly to tale his food without taking a tray so something must be wrong in the class function but I can't figure what.
import threading
import random
import time
import concurrent.futures
import traceback
class Queue:
def __init__(self) -> None:
self.list_of_products = []
self.queue = []
self.lock = threading.Lock()
self.bill = 0
self.type_of_products = random.randrange(1, 4)
def add_client(self, client):
self.lock.acquire()
self.queue.append(client)
self.lock.release()
def remove_client(self, client):
self.lock.acquire()
self.queue.remove(client)
self.lock.release()
def check_if_client_in_queue(self, client) -> bool:
self.lock.acquire()
student_in_queue = True if client in self.queue else False
self.lock.release()
return student_in_queue
def check_if_empty(self) -> bool:
self.lock.acquire()
empty = len(self.queue) == 0
self.lock.release()
return empty
def get_first_client(self):
if not self.check_if_empty():
return self.queue.pop(0)
return None
def result_of_random_range(self):
x = self.type_of_products
return x
def paying(self):
self.lock.acquire()
if self.type_of_products == 1:
self.list_of_products.append(self.type_of_products)#i think it is not appending
self.bill = 1 * 25.90
elif self.type_of_products == 2:
self.list_of_products.append(self.type_of_products)
self.bill = 1 * 17.90
else:
self.list_of_products.append(self.type_of_products)
self.bill = 1 * 13.50
type_of_payment = random.randrange(1, 3)
if type_of_payment == 1:
print("Client has to pay", self.bill, "and he is paying in cash")
change = random.randrange(int(self.bill), round(int(self.bill) + 5)) - int(self.bill)
print("Amount to be returned", change, "€")
else:
print("Client has to pay", self.bill, "and he is paying with his credit card")
self.lock.release()
return self.bill
def tray(self):
self.lock.acquire()
random_fall = random.randrange(1,25)
if random_fall != 1:
print("Client got his Tray")
else:
print("Client dropped his tray")
time.sleep(10)
self.lock.release()
class Clients:
def __init__(self, id, queues):
self.id = id
self.queues = queues
if random.randrange(1, 3) == 1:
self.queues["clients_waiting_to_pay_manually"].add_client(self)
else:
self.queues["clients_waiting_to_pay_automatically"].add_client(self)
def __str__(self) -> str:
return f"{self.id}"
def change_queues(self) -> None:
try:
while True:
if not self.queues["clients_waiting_to_pay_manually"].check_if_client_in_queue(self) and not \
self.queues["clients_waiting_to_pay_automatically"].check_if_client_in_queue(self):
break
change_criteria = random.randrange(1, 10)
if change_criteria != 1:
time.sleep(1)
continue
print(f"Client with id {self.id} is gonna switch queue")
if self.queues["clients_waiting_to_pay_manually"].check_if_client_in_queue(self):
self.queues["clients_waiting_to_pay_manually"].remove_client(self)
self.queues["clients_waiting_to_pay_automatically"].add_client(self)
time.sleep(1)
continue
if self.queues["clients_waiting_to_pay_automatically"].check_if_client_in_queue(self):
self.queues["clients_waiting_to_pay_automatically"].remove_client(self)
self.queues["clients_waiting_to_pay_manually"].add_client(self)
time.sleep(1)
continue
except Exception:
traceback.print_exc()
class Station:
def __init__(self, id, queues):
self.id = id
self.queues = queues
def moving_station(self):
try:
while True:
if not self.queues["clients_waiting_to_pay_automatically"].check_if_empty():
client = self.queues["clients_waiting_to_pay_automatically"].get_first_client()
print(f"Cashier {self.id}: Serving the client {client} in the automatic queue")
self.queues["clients_waiting_to_pay_automatically"].paying()
print(f"Client {client} has paid and is going to another station ")
self.queues["clients_getting_main_food"].add_client(client)
print(f"Client {client} is getting his food ")
time.sleep(2)
elif not self.queues["clients_waiting_to_pay_manually"].check_if_empty():
client = self.queues["clients_waiting_to_pay_manually"].get_first_client()
print(f"Cashier {self.id}: Serving the client {client} in the manual queue")
self.queues["clients_waiting_to_pay_manually"].paying()
print(f"Client {client} has paid and is going to another station ")
self.queues["clients_getting_main_food"].add_client(client)
print(f"Client {client} is getting his food ")
time.sleep(2)
else:
break
except Exception:
traceback.print_exc()
class Trays:
def __init__(self,queues) -> None:
self.queues = queues
def giving_trays(self):
try:
while True:
if self.queues["clients_waiting_for_tray"].check_if_empty():
print(f"There is no more clients waiting for a tray")
break
elif not self.queues["clients_waiting_for_tray"].check_if_empty():
client = self.queues["clients_waiting_for_tray"].get_first_client()
print(f"{client} got his tray")
print(f"Client {client} just got his tray")
time.sleep(2)
else:
break
except Exception as e:
traceback.print_exc()
class Main_food:
def __init__(self,id,queues):
self.id = id
self.queues = queues
def getting_food(self):
pasta_menu = ["Carbonara ", "Pesto", "Basilico", "Bolognese", "Truffle", "Chicken Alfredo"]
protein_menu = ["Beef","Pork","Fish","chicken","Beyond Meat","turkey"]
pasta_stock = [2,1,4,5,6,3]
protein_stock = [2,1,4,5,6,3]
try:
if not self.queues["clients_getting_main_food"].check_if_empty():
client_getting_served = self.queues["clients_getting_main_food"].get_first_client()
if self.queues["clients_waiting_to_pay_automatically"].result_of_random_range() == 1:
self.queues["clients_getting_menu_1"].add_client(client_getting_served)
elif self.queues["clients_waiting_to_pay_manually"].result_of_random_range() == 1:
self.queues["clients_getting_menu_1"].add_client(client_getting_served)
if self.queues["clients_waiting_to_pay_automatically"].result_of_random_range() == 2:
self.queues["clients_getting_menu_2"].add_client(client_getting_served)
elif self.queues["clients_waiting_to_pay_manually"].result_of_random_range() == 2:
self.queues["clients_getting_menu_2"].add_client(client_getting_served)
elif self.queues["clients_waiting_to_pay_manually"].result_of_random_range() == 3:
self.queues["clients_getting_menu_3"].add_client(client_getting_served)
else:
self.queues["clients_getting_menu_3"].add_client(client_getting_served)
x = random.randrange(0,6)
y = random.randrange(0,6)
stock = pasta_stock[x]
stock1 = protein_stock[y]
if not self.queues["clients_getting_menu_1"].check_if_empty():
client_being_served_1 = self.queues["clients_getting_menu_1"].get_first_client()
if stock != 0:
pasta_stock[x] = pasta_stock[x]-1
if stock1 != 0:
protein_stock[y] = protein_stock[y]-1
print(f"Client {client_being_served_1} is getting Pasta : {pasta_menu[x]} and Protein : {protein_menu[y]}")
print(f"pasta {pasta_stock[x]} protein {protein_stock[y]} ")
self.queues["clients_getting_desert"].add_client(client_being_served_1)
if not self.queues["clients_getting_menu_2"].check_if_empty():
client_being_served_2 = self.queues["clients_getting_menu_2"].get_first_client()
if stock != 0:
pasta_stock[x] = pasta_stock[x]-1
print(f"Client {client_being_served_2} is getting Pasta :{pasta_menu[x]}")
print(f"pasta2 {pasta_stock[x]} ")
self.queues["clients_getting_desert"].add_client(client_being_served_2)
elif not self.queues["clients_getting_menu_3"].check_if_empty():
client_being_served_3 = self.queues["clients_getting_menu_3"].get_first_client()
if stock1 != 0:
protein_stock[y] = protein_stock[y]-1
print(f"Client {client_being_served_3} is getting Protein :{protein_menu[y]}")
print(f"protein3 {protein_stock[y]} ")
self.queues["clients_getting_desert"].add_client(client_being_served_3)
except Exception as e:
traceback.print_exc()
queues ={
"clients_waiting_to_pay_manually": Queue(),
"clients_waiting_to_pay_automatically": Queue(),
"clients_waiting_for_tray": Queue(),
"clients_getting_main_food": Queue(),
"clients_not_getting_main_food": Queue(),
"clients_getting_menu_1": Queue(),
"clients_getting_menu_2": Queue(),
"clients_getting_menu_3": Queue(),
"clients_getting_desert": Queue()
}
number_of_cashiers = 3
number_of_clients = 10
clients = [Clients(id, queues) for id in range(number_of_clients)]
stations = [Station(id, queues) for id in range(number_of_clients)]
trays = [Trays(queues) for id in range(number_of_clients)]
foods = [Main_food(id, queues) for id in range(number_of_clients)]
with concurrent.futures.ThreadPoolExecutor(max_workers=number_of_clients) as executor:
for client in clients:
executor.submit(client.change_queues)
with concurrent.futures.ThreadPoolExecutor(max_workers=number_of_clients) as executor:
for station in stations:
executor.submit(station.moving_station)
with concurrent.futures.ThreadPoolExecutor(max_workers=number_of_clients) as executor:
for tray in trays:
executor.submit(tray.giving_trays)
with concurrent.futures.ThreadPoolExecutor(max_workers=number_of_clients) as executor:
for food in foods:
executor.submit(food.getting_food)

OSError: [WinError 10038] An operation was attempted on something that is not a socket what is the problem?

im running a chat app on my computer and i tried to send a message and this ERROR accured. it suppose to send a " will joind the chat" and another message " connected to server" after that i should send my message to the group and it didnt worked.
any ideas?
import kivy
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
import socket
import threading
kivy.require("1.9.0")
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
class MyRoot(BoxLayout):
def __init__(self):
super(MyRoot, self).__init__()
def send_message(self):
client.send(f"{self.nickname_text.text}: {self.message_text.text}".encode('utf-8'))
def connect_to_server(self):
if self.nickname_text != "":
client.connect((self.ip_text.text, 9999))
message = client.recv(1024).decode('utf-8')
if message == "NICK":
client.send(self.nickname_text.text.encode('utf-8'))
self.send_btn.disabled = False
self.message_text.disabled = False
self.connect_btn.disabled = True
self.ip_text.disabled = True
self.make_invisible(self.connection_grid)
self.make_invisible(self.connect_btn)
thread = threading.Thread(target=self.receive)
thread.start()
def make_invisible(self, widget):
widget.visible = False
widget.size_hint_x = None
widget.size_hint_y = None
widget.height = 0
widget.width = 0
widget.text = ""
widget.opacity = 0
def receive(self):
stop = False
while not stop:
try:
message = client.recv(1024).decode('utf-8')
self.chat_text.text += message + "\n"
except:
print("ERROR")
client.close()
stop = True
class TraboChat(App):
def build(self):
return MyRoot()
trabo_chat = TraboChat()
trabo_chat.run()
serve.py:
import socket
import threading
HOST = socket.gethostbyname(socket.gethostname())
PORT = 9999
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((HOST, PORT))
server.listen()
clients = []
nicknames = []
def broadcast(message):
for client in clients:
client.send(message)
def handle_connection(client):
stop = False
while not stop:
try:
message = client.recv(1024)
broadcast(message)
except:
index = clients.index(client)
clients.remove(client)
nickname = nicknames[index]
nicknames.remove(nickname)
broadcast(f"{nickname} left the chat!".encode('utf-8'))
stop = True
def main():
print("server is running..")
while True:
client, addr = server.accept()
print(f"connected to {addr}")
client.send("NICK".encode('utf-8'))
nickname = client.recv(1024).decode('utf-8')
nicknames.append(nickname)
clients.append(client)
print(f"Nickname is {nickname}")
broadcast(f"{nickname} join the chat!")
client.send("You are now connected".encode('utf-8'))
thread = threading.Thread(target=handle_connection, args=(client,))
if name == 'main':
main()

NameError: global name 'Carnage' is not defined

I know it was asked a million times before, but I need a little help getting this working, as the code is not mine.
so like that i update a code hope it will make some undarstands of it
# coding=utf-8
import urllib, re, sys, threading, cookielib, urllib2
from BeautifulSoup import BeautifulSoup
### Головная функция
def main():
agent = 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)'
aCarnage = Carnage('YourNick', 'YourPass', 'arkaim.carnage.ru', 'cp1251', agent)
aCarnage.login()
me = aCarnage.inf(aCarnage.user)
# Если ранен - выйти
if me['inj']:
aCarnage.logout()
exit(1)
aCarnage.urlopen('main.pl')
# Подождать пока здоровье восстановится
while(me['hp_wait']):
time.sleep(me['hp_wait'])
me = aCarnage.inf(aCarnage.user)
# Найти подходящую заявку
aCarnage.find()
me = aCarnage.inf(aCarnage.user)
# Если заявка состоялась - в бой!
if me['battle']: aCarnage.fight()
# После боя - выход из игры
aCarnage.logout()
class Opener:
def __init__(self, host, encoding, agent):
self.host = host
self.encoding = encoding
self.agent = agent
self.opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookielib.CookieJar()))
def urlopen(self, goto, data = None):
f = self.opener.open(urllib2.Request(
"http://%s/%s" % (self.host, goto),
self.urlencode(data),
{"User-agent" : self.agent}
))
result = f.read()
self.soup = BeautifulSoup(result)
def urlencode(self, data):
if data is None: return None
for key in data:
data[key] = data[key].encode(self.encoding, 'ignore')
return urllib.urlencode(data)
class CarnageBot(Opener):
### Конструктор принимает логин, пароль, кодировку (cp1251) и идентификатор браузера
def __init__(self, user, password, host, encoding, agent):
self.user = user
self.password = password
Opener.__init__(self, host, encoding, agent)
### Получить информацию об игроке - например о самом себе
def inf(self, user):
self.urlopen('inf.pl?' + self.urlencode({'user': user}))
# Кол-во жизни
onmouseover = self.soup.find('img', onmouseover = re.compile(unicode('Уровень жизни:', 'utf8')))
m = re.search('([0-9]+).([0-9]+)', onmouseover['onmouseover'])
hp = int(m.group(1))
hp_max = int(m.group(2))
hp_wait = (100 - (hp * 100) / hp_max) * 18
# Уровень
td = self.soup.find('td', text = re.compile(unicode('Уровень:', 'utf8')))
level = int(td.next.string)
# Ранен или нет
inj = 0
if self.soup.find(src = re.compile(unicode('travma.gif', 'utf8'))): inj = 1
# В бою или нет
battle = 0
if self.soup.find(text = re.compile(unicode('Персонаж находится в бою', 'utf8'))): battle = 1
hero = {'level': level, 'hp': hp, 'hp_max': hp_max, 'hp_wait': hp_wait, 'inj': inj, 'battle': battle}
return hero
### Войти в игру
def login(self):
data = {'action': 'enter', 'user_carnage': self.user, 'pass_carnage': self.password}
self.urlopen('enter.pl', data)
self.urlopen('main.pl')
### Выйти из игры
def logout(self):
self.urlopen('main.pl?action=exit')
### В бой!!!
def fight(self):
self.urlopen('battle.pl')
while True:
# Добить по таймауту
if self.soup.find(text = re.compile(unicode('Противник потерял сознание', 'utf8'))):
self.urlopen('battle.pl?cmd=timeout&status=win')
break
if self.soup.find(text = re.compile(unicode('Бой закончен.', 'utf8'))):
break
reg = re.compile(unicode('Для вас бой закончен. Ждите окончания боя.', 'utf8'))
if self.soup.find(text = reg):
break
cmd = self.soup.find('input', {'name' : 'cmd', 'type' : 'hidden'})
to = self.soup.find('input', {'name' : 'to', 'type' : 'hidden'})
# Есть ли по кому бить?!
if cmd and to:
a = random.randint(1, 4)
b0 = random.randint(1, 4)
b1 = random.randint(1, 4)
while b1 == b0: b1 = random.randint(1, 4)
pos = 2
arg = (cmd['value'], to['value'], pos, a, a, b0, b0, b1, b1)
self.urlopen('battle.pl?cmd=%s&to=%s&pos=%s&A%s=%s&D%s=%s&D%s=%s' % arg)
else:
self.urlopen('battle.pl')
time.sleep(random.randint(5, 30))
### Найти заявку - подающий заявку должен быть на 1 уровень ниже нашего
def find(self):
me = self.inf(self.user)
while True:
v = ''
self.urlopen('zayavka.pl?cmd=haot.show')
reg = re.compile(unicode('Текущие заявки на бой', 'utf8'))
script = self.soup.find('fieldset', text = reg).findNext('script')
m = re.findall('.*', script.string)
for value in m:
if value.find('group.gif') < 0: continue
if value.find('(%i-%i)' % (me['level'] - 2, me['level'])) < 0: continue
t = re.search(',([0-9]{1,2}),u', value)
if not t: continue
t = int(t.group(1))
v = re.search('tr\(([0-9]+)', value).group(1)
print 'Found battle t=%i v=%s' % (t, v)
break
if v: break
time.sleep(80)
nd = self.soup.find('input', {'name' : 'nd', 'type' : 'hidden'})
self.urlopen('zayavka.pl?cmd=haot.accept&nd=%s&battle_id=%s' % (nd['value'], v))
time.sleep(t + 30)
if __name__ == '__main__': main()
The error is:
NameError: global name 'Carnage' is not defined
The cause of your error is that Carnage has not been defined. Maybe you forgot to import a library which provides Carnage?
Also, your code as posted is incorrectly indented, which is a syntax error.
Update: Apparently you took this code from http://github.com/Ejz/Common/tree/master/carnage-bot . Reading that source, it looks like the line
aCarnage = Carnage('YourNick', 'YourPass', 'arkaim.carnage.ru', 'cp1251', agent)
Should be
aCarnage = CarnageBot('YourNick', 'YourPass', 'arkaim.carnage.ru', 'cp1251', agent)
Because the methods called on aCarnage are defined further down the file for class CarnageBot.