I want to check if the token of a Telegram bot is real.
I tried this:
try:
bot = telepot.Bot(token)
except:
pprint("Il token inserito non è valido! Riavvia il programma e inserisci un altro token!")
ftok = open('C:/Limitatibot/token.txt','w')
ftok.write('')
ftok.close()
pprint('Premere un tasto per continuare...')
input()
quit()
But it didn't work :C. How could it be solved?
Related
I was working with fernet to encrypt. In the tests I founded that if I change the last character of the key, fernet it is able to dencrypt.
For example if the key is ZwvCXUGvnG0RvkhNszIQsQOqz8yaKjUSJpxraDVsxd4= and i type ZwvCXUGvnG0RvkhNszIQsQOqz8yaKjUSJpxraDVsxd5= instead, the program dencrypt my code. I founded this error bc i was lazy to copy a whole new key, so i decided to only change the last character. This happen with every consecuent character in the last one character of the key.
If anyone could help me i would be very thankfull
This is my code
from cryptography.fernet import Fernet
text1="""Find me and follow me through corridors, refectories and files
You must follow, leave this academic factory
You'll find me in the matinée, the dark of the matinée
It's better in the matinée, the dark of the matinée is mine
Yes, it's mine"""
def crearLLave():
key=Fernet.generate_key()
print(key.decode())
return Fernet(key)
def crearLLaveManual(llave):
try:
return Fernet(llave)
except:
again=bytes(input("Formato incorrecto "), "ascii")
return crearLLaveManual(again)
def encriptarTexto(cadena, llave):
return llave.encrypt(str.encode(cadena))
def desencriptarTexto(cadena_encriptada, llave):
try:
return llave.decrypt(cadena_encriptada).decode()
except:
cadena=bytes(input("La cámara de los secretos no se abrirá, intente de nuevo: "),"ascii")
return desencriptarTexto(cadena_encriptada, crearLLaveManual(cadena))
llave=crearLLave()
texto_encriptado=encriptarTexto(text1, llave)
print("La cadena encriptada es: ",texto_encriptado.decode())
cadenaLlave=bytes(input("Escriba la llave para desencriptar el texto: "), "ascii")
llaveManual=crearLLaveManual(cadenaLlave)
print("El texto desencriptado es: ",desencriptarTexto(texto_encriptado, llaveManual))
Console Message:
lIX2AfP-cyFRNgYgFRf3Sy3uKQ4Hrr4Lvrn12wFGo30=
La cadena encriptada es: gAAAAABjg7kdWTCIRjIrIAFk2fQg-znc1zRdrc7VaTkjcKZL1RZ2jmCjvf6NlzQ-39yxh0BMXY0FkrBTN0Ky51HiGy9cxmlbpZ7_Jwp6wml2DsMkCWf7h49EYLN8hjtpzFoiTUy7coguSXgFDBVVyucAUhgcn1EzleHJ_pKlDsyw6EnNLVBqUkmI8WYOY5NwEfCKx3UUlvV3dYDZqjeVqMX90CaAueUMtgDvcVP77tkngK7U2jfneH85bxBo8LJooenFnVeqNxwc70a8vY-GmOihnbDyAOT-GYwmLMssMP5QYDWNBnnTEmMSm4Dt-OHCvOYRyie82T6Art6PK5miinVsjsvkXpd6g343tmNSg34XMbMqgTIILXB7t6gZqdfnpUNUJ6vLfQvM4s4bYSltEEgTSIwrMUUUbA==
Escriba la llave para desencriptar el texto: lIX2AfP-cyFRNgYgFRf3Sy3uKQ4Hrr4Lvrn12wFGo31=
El texto desencriptado es: Find me and follow me through corridors, refectories and files
You must follow, leave this academic factory
You'll find me in the matinée, the dark of the matinée
It's better in the matinée, the dark of the matinée is mine
Yes, it's mine
I'm trying to create a remote using my phone for a game with sockets and pynput. Although some apps such as Chrome or Notepad detect and display the keys that have been pressed with the controller function of pynput (press and release), other ones (such as vba-m, the program I was interested in) just don't register any input. I've tried running the script with admin priviledges, but nothing has changed.
This is the code I'm using:
import socket,threading
from pynput.keyboard import Key, Controller
PORT=12345
SERVER="192.168.1.160"
ADDR=(SERVER, PORT)
FORMAT="utf-8"
TERMINATED="ADIOS"
server=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(ADDR)
conectados=[]
conectadosaddr=[]
keyboard = Controller()
def start(): #Función que se encarga de iniciar el servidor y escuchar nuevas conexiones
server.listen()
print("Servidor iniciado")
while True:
conn,addr=server.accept()
conectados.append(conn)
conectadosaddr.append(addr)
thread=threading.Thread(target=handle_client, args=(conn, addr))
thread.daemon=True
thread.start()
print(f"Conexiones activas: {len(conectados)}")
def handle_client(conn, addr): #Función que se encarga de manejar las conexiones
print(f"Nueva conexion de {addr}")
connected=True
while connected:
try:
data=conn.recv(1024).decode(FORMAT)
if data:
print(f"Recibido: {data} de {addr}")
if data==TERMINATED:
connected=False
print("Se ha cerrado la conexion pacíficamente de "+str(addr))
elif data in "WASDZX":
keyboard.press(data)
keyboard.release(data)
elif data=="BK":
keyboard.press(Key.backspace)
keyboard.release(Key.backspace)
elif data=="ST":
keyboard.press(Key.enter)
keyboard.release(Key.enter)
except Exception as e:
connected=False
print("ERROR: ",e)
print(f"{addr} se ha desconectado")
conectados.remove(conn)
conectadosaddr.remove(addr)
conn.close()
if __name__ == '__main__':
start()
I managed to fix the issue using a different library, called "pydirectinput". It does the same thing pynput does, but its presses are detected by vba-m and many other videogames
I'm coding 10 discord bots for fun, all of these have the same code, (but different token) how can I run all bots with 1 code? Thank you.
import random
import time
import discord
from discord.ext import commands
messaggio = "ti sto dando fastidio?"
client = client = commands.Bot(command_prefix = "()")
Client = discord.Client()
#client.event
async def on_ready():
print("Sono online e pronto ad infastidire")
#client.command() #Invia messaggi in privato ad un utente taggato.
async def infastidisci(ctx, member : discord.Member, numero_di_messaggi = 1):
for x in range(numero_di_messaggi):
y = random.uniform(0.25, 1.50)
time.sleep(y)
print(f"Messaggio inviato a {member}. Messaggi restanti: ", numero_di_messaggi - x - 1)
await member.send(messaggio)
#client.command()
async def infastidisci_chat(ctx, numero_di_messaggi = 1):
for x in range(numero_di_messaggi):
messaggio_fastidioso = "#everyone vi sto dando fastidio?"
canali = ctx.message.guild.text_channels
y = random.uniform(0.25, 1.50)
time.sleep(y)
for canale in canali:
await canale.send(messaggio_fastidioso)
print(f"Messaggio inviato in {canale}. Messaggi restanti: {numero_di_messaggi - x -1}")
client.run(token)
One method:
You retrieve the token from an environment variable:
import os
token = os.environ.get("TOKEN", None)
You execute your program from command line with:
TOKEN=mytoken python3 main.py
What changed here is you have to define the environment variable TOKEN.
Now you can just execute the process multiple time. You can also wrap it in a single command line
TOKEN=mytoken1 python3 main.py & TOKEN=mytoken2 python3 main.py
so I have a simple code that create a graphical interface with Tkinter on python, but when I convert it to exe using PyInstaller I get this issue , I don't understand what's happening
Error loading Python lib '/Users/salwafakhir/dist/app/Python': dlopen: dlopen(/Users/salwafakhir/dist/app/Python, 10): no suitable image found. Did find:
/Users/salwafakhir/dist/app/Python: code signature invalid for '/Users/salwafakhir/dist/app/Python'
here is a part of the code
creer une premiere fenetre
masterWindow= Tk()
#personnaliser ma fenetre
masterWindow.title("logistics interface")
masterWindow.geometry("1280x1024")
masterWindow.minsize(480 , 360)
masterWindow.config(background='white')
#creer frame
frameProduct_1W=Frame(masterWindow,bg='white')
image = PhotoImage(file="/Users/salwafakhir/Desktop/seaver-sangle-connecte-equitation-technologie.png")
label = Label(image=image)
label.pack(expand=YES)
#ajouter un premier texte
Label_title =Label(frameProduct_1W,text="Welcome to SeaverLogictec",font=("Time New Roman",40),bg='white', fg="#3A67C1").pack(expand=YES)
ajouter un second texte
Label_subtitle =Label(frameProduct_1W,text="We are here to help you with Stock management and order placing ",font=("Time New Roman",15),bg='white', fg="#3A67C1").pack(expand=YES)
#connection a la base de donne logistic
conn = MongoClient()
db = conn.admin
#ajouter un premier bouton
startButton= Button(frameProduct_1W,text="Let's get started",font=("Time New Roman",40),bg='white', fg='#3A67C1', command=open).pack(expand=YES)
#ajouter frameProduct_1W
frameProduct_1W.pack(expand=YES)
#afficher
masterWindow.mainloop()
I have been doing some port-reading for work, and I need to know if I should use asyncIO to read the data that comes in from this port.
Here's some details about the way in which the system is constructed.
Multiple sensors are being read at the same time and might produce output that goes in at the same time. (all data comes in through a probee ZU10 connected to a usb port) All data must be timestamped as soon as it comes in.
The data is supposed to be processed and then sent to a django webapp through a REST API.
The thing Is, it's really important not to lose any data, I'm asking about this because I believe there must be an easier way to do this than the one I'm thinking of.
The way I want the data to come in is through an asyncronous process that takes in the data into a queue and timestamps it, this way there is no way in which loss of data is present, and timestamping may be no more than a few fractions of a second off, which is not a problem.
If anyone has got any ideas I would be thankful for them
Here's the code I'm using to open the port, take the data in and what I've got so far on the actually reading the meaningful data.
Here's the reading part:
import serial #for port opening
import sys #for exceptions
#
#configure the serial connections (the parameters differs on the device you are connecting to)
class Serializer:
def __init__(self, port, baudrate=9600, timeout=.1):
self.port = serial.Serial(port = port, baudrate=baudrate,
timeout=timeout, writeTimeout=timeout)
def open(self):
''' Abre Puerto Serial'''
self.port.open()
def close(self):
''' Cierra Puerto Serial'''
self.port.close()
def send(self, msg):
''' envía mensaje a dispositivo serial'''
self.port.write(msg)
def recv(self):
''' lee salidas del dispositivo serial '''
return self.port.readline()
PORT = '/dev/ttyUSB0' #Esto puede necesitar cambiarse
# test main class made for testing
def main():
test_port = Serializer(port = PORT)
while True:
print(test_port.recv())
if __name__ == "__main__":
main()
And a bit of what I'm going to be using to filter out the meaningful reads (bear with it, it might be full of awful errors and maybe a terrible RegEx):
import re
from Lector import ChecaPuertos
from Lector import entrada
patterns = [r'^{5}[0-9],2[0-9a-fA-F] $'] #pattern list
class IterPat:
def __init__(self, lect, pat = patterns):
self.pat = pat # lista de patrones posibles para sensores
self.lect = lect # lectura siendo analizada
self.patLen = len(pat) #Largo de patrones
def __iter__(self):
self.iteracion = 0 #crea la variable a iterar.
def __next__(self):
'''
Primero revisa si ya pasamos por todas las iteraciones posibles
luego revisa si la iteración es la que pensabamos, de ser así regresa una
tupla con el patrón correspondiente, y la lectura
de otra forma para el valor de ser mostrado
'''
pattern = re.compile(self.pat[self.iteracion])
comp = pattern.match(self.lect)
if comp == True:
re_value = (self.pattern, self.lect)
return re_value
else:
self.iteración += 1
def main():
puerto = ChecaPuertos.serial_ports()
serial = entrada.Serializer(port = puerto[0])
if serial != open:
serial.open()
while True:
iter = IterPat()
#This is incomplete right here.
I am using asyncio to read/write a serial port with pyserial. I am having my device on the other end of the serial connection write a single byte when it is ready to receive a payload. Asyncio watches for that byte then sends the payload. It looks something like this:
serial_f = serial.Serial(port=dev, baudrate=BAUDRATE, timeout=2)
def write_serial():
status = serial_f.read(1)
serial_f.write(buffer)
loop = asyncio.get_event_loop()
loop.add_reader(serial_f.fileno(), write_serial)