My Daily Gist | Ferdinand Silva


Town of Salem Echo And Auto Greeter Bot

 
#!/usr/bin/env python
"""
Note:
-----
* Install pycrypto
"""
import socket
import re
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_v1_5 as Cipher_PKCS1_v1_5
from base64 import b64decode,b64encode
from getpass import getpass
def encrypt_password(password):
pubkey = 'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAziIxzMIz7ZX4KG5317Sm\nVeCt9SYIe/+qL3hqP5NUX0i1iTmD7x9hFR8YoOHdAqdCJ3dxi3npkIsO6Eoz0l3e\nH7R99DX16vbnBCyvA3Hkb1B/0nBwOe6mCq73vBdRgfHU8TOF9KtUOx5CVqR50U7M\ntKqqc6M19OZXZuZSDlGLfiboY99YV2uH3dXysFhzexCZWpmA443eV5ismvj3Nyxv\nRk/4ushZV50vrDjYiInNEj4ICbTNXQULFs6Aahmt6qmibEC6bRl0S4TZRtzuk2a3\nTpinLJooDTt9s5BvRRh8DLFZWrkWojgrzS0sSNcNzPAXYFyTOYEovWWKW7TgUYfA\ndwIDAQAB'
keyDER = b64decode(pubkey)
keyPub = RSA.importKey(keyDER)
cipher = Cipher_PKCS1_v1_5.new(keyPub)
cipher_text = cipher.encrypt(password.encode())
return b64encode(cipher_text)
def addFriend(tosSocket, friendRequest, friendsList):
if raw_input("Do you want to add %s as your friend? [y/n]: " % friendRequest["username"]).strip().lower() == "y":
# accept friend
acceptMessage = chr(26) + friendRequest["username"] + "*" + friendRequest["id"] + chr(0)
tosSocket.send(acceptMessage.encode())
# add to friends list
friendsList[friendRequest["id"]] = {
"username": friendRequest["username"],
"status": False
}
else:
# deny friend
denyMessage = chr(28) + friendRequest["id"] + chr(0)
tosSocket.send(denyMessage.encode())
TOS_HOST = "live4.tos.blankmediagames.com"
TOS_PORT = 3600
TOS_BUILD_ID = "11704"
if __name__ == "__main__":
print """
********** ******* ******** ****** **
/////**/// **/////** **////// /*////** /**
/** ** //**/** /* /** ****** ******
/** /** /**/********* /****** **////**///**/
/** /** /**////////** /*//// **/** /** /**
/** //** ** /** /* /**/** /** /**
/** //******* ******** /******* //****** //**
// /////// //////// /////// ////// //
"""
print ""
tos_username = raw_input("Please enter your username: ").strip()
tos_password = encrypt_password(getpass("Please enter your password: ").strip())
tosSocket = socket.socket()
tosSocket.connect((TOS_HOST, TOS_PORT))
msgByte = chr(2) + chr(2) + chr(2) + chr(1) + TOS_BUILD_ID + chr(30) + tos_username + chr(30) + tos_password + chr(0)
tosSocket.send(msgByte.encode())
loggedIn = False
needToBreak = False
messageStr = ""
nullCount = 0
gotFriendsList = False
friendsList = {}
friendsRequest = []
startProcess = False
try:
while True:
data = tosSocket.recv(1024)
for ch in data:
if ord(ch) == 226:
if not loggedIn:
print "Invalid login..."
else:
print "Disconnected from server..."
tosSocket.close()
needToBreak = True
break
if ord(ch) == 1 and not loggedIn:
loggedIn = True
print "You are connected to the server..."
if loggedIn and ord(ch) != 0:
messageStr += ch
if loggedIn and ord(ch) == 0:
#print messageStr
nullCount += 1
if nullCount > 12 and not gotFriendsList:
if re.search(",", messageStr):
# make sure that the line you are reading is not a friend request
if re.search("\x01", messageStr) or re.search("\x03", messageStr):
# get friends list
splittedInfos = messageStr.split(',')
# '\x01' - offline
# '\x03' - online
countInfo = 0
currentUser = ""
currentID = ""
for splittedInfo in splittedInfos:
try:
if countInfo == 0:
currentUser = splittedInfo.replace("1*", "").replace("\x14", "")
countInfo += 1
elif countInfo == 1:
currentID = splittedInfo
countInfo += 1
next
else:
friendsList[currentID] = {
"username": currentUser,
"status": True if splittedInfo == '\x03' else False
}
countInfo = 0
currentID = ""
currentUser = ""
except:
break
# list friends
print "\nYour friends are:"
print "-----------------\n"
for k,v in friendsList.items():
print "%s with ID : %s and status: %s" % (v["username"], k, "Online" if v["status"] else "Offline")
print "\n\n"
gotFriendsList = True
else:
# add friend requests (notification)
requests = messageStr.split("*")
for request in requests:
info = request.split(",")
friendsRequest.append({
"username": info[0].replace("\x15", ""),
"id": info[1]
})
elif gotFriendsList:
if startProcess:
if re.search("\*0\*", messageStr): # friend private message
messageStr = messageStr.replace(chr(27), "")
splittedMessage = messageStr.split("*0*")
for k, v in friendsList.items():
if re.search(splittedMessage[0][1:], k):
print "%s says: %s" % (friendsList[k]["username"], splittedMessage[1])
echoMessage = chr(29) + '%s*Your message is: "%s"' % (friendsList[k]["username"], splittedMessage[1]) + chr(0)
tosSocket.send(echoMessage.encode())
break
elif re.search(chr(2) + "\*1", messageStr): # online status
user_id = messageStr.split("*")
user_id = user_id[0].replace("\x1a", "")
for k, v in friendsList.items():
if re.search(user_id, k):
friendsList[k]["status"] = True
print "%s status: %s" % (friendsList[k]["username"], "Online")
# send auto greet
greetingMessage = chr(29) + '%s*Mabuhay! Welcome to Town of Salem!' % friendsList[k]["username"] + chr(0)
tosSocket.send(greetingMessage.encode())
break
elif re.search(chr(1) + "\*1", messageStr): # offline status
user_id = messageStr.split("*")
user_id = user_id[0].replace("\x1a", "")
for k, v in friendsList.items():
if re.search(user_id, k):
friendsList[k]["status"] = False
print "%s status: %s" % (friendsList[k]["username"], "Offline")
break
elif re.search(chr(24), messageStr): # deleted you as a friend
friendID = messageStr.replace(chr(24), "")
print "%s deleted you as a friend" % friendsList[friendID]["username"]
del friendsList[friendID]
elif re.search(chr(21), messageStr): # add friend request
info = messageStr.replace(chr(21), "").split(",")
addFriend(tosSocket, {"username": info[0], "id": info[1]}, friendsList)
else:
if len(friendsRequest) > 0:
print "Notification/s"
print "--------------\n\n"
for friendRequest in friendsRequest:
addFriend(tosSocket, friendRequest, friendsList)
print ""
startProcess = True
messageStr = ""
if needToBreak:
break
except KeyboardInterrupt:
tosSocket.close()

My Hello World Code In Assembly Language On Mac OS X

 
; Assembling and linking
; ----------------------
; nasm -f macho64 test.asm
; gcc -o test test.o -Wl,-no_pie
section .data ; data section
line1:
db "My name is: " ; constant string
line2:
db "Ferdinand", 0xA ; constant string with newline
global _main
section .text ; text section
_main:
mov rax, 0x2000004 ; syscall number for write
mov rdi, 1 ; set first parameter to 1 (standard output)
mov rsi, line1 ; set second parameter to line1 constant string
mov rdx, 12 ; set third parameter (buffer size)
syscall ; invoke write function
mov rax, 0x2000004 ; syscall number for write
mov rdi, 1 ; set first parameter to 1 (standard output)
mov rsi, line2 ; set second parameter to line2 constant string
mov rdx, 10 ; set third parameter (buffer size)
syscall ; invoke write function
mov rax, 0x2000001 ; syscall number for exit
mov rdi, 0 ; set first parameter to 0 (return 0 to OS)
syscall ; invoke exit function
view raw test.asm hosted with ❤ by GitHub

Windows API Implementation In Go Sample Code (Change Console Text Color)

 
package main
import (
"fmt"
"syscall"
"unsafe"
)
const (
FOREGROUND_BLACK uint16 = 0x0000
FOREGROUND_BLUE uint16 = 0x0001
FOREGROUND_GREEN uint16 = 0x0002
FOREGROUND_CYAN uint16 = 0x0003
FOREGROUND_RED uint16 = 0x0004
FOREGROUND_PURPLE uint16 = 0x0005
FOREGROUND_YELLOW uint16 = 0x0006
FOREGROUND_WHITE uint16 = 0x0007
)
type (
SHORT int16
WORD uint16
SMALL_RECT struct {
Left SHORT
Top SHORT
Right SHORT
Bottom SHORT
}
COORD struct {
X SHORT
Y SHORT
}
CONSOLE_SCREEN_BUFFER_INFO struct {
Size COORD
CursorPosition COORD
Attributes WORD
Window SMALL_RECT
MaximumWindowSize COORD
}
)
func main() {
var consoleInfo CONSOLE_SCREEN_BUFFER_INFO
kernel32 := syscall.NewLazyDLL("kernel32.dll")
getConsoleScreenBufferInfoProc := kernel32.NewProc("GetConsoleScreenBufferInfo")
setConsoleTextAttributeProc := kernel32.NewProc("SetConsoleTextAttribute")
handle, _ := syscall.GetStdHandle(syscall.STD_OUTPUT_HANDLE)
_, _, _ = getConsoleScreenBufferInfoProc.Call(uintptr(handle), uintptr(unsafe.Pointer(&consoleInfo)), 0)
fmt.Println("Original Color")
//set to yellow
_, _, _ = setConsoleTextAttributeProc.Call(uintptr(handle), uintptr(FOREGROUND_YELLOW), 0)
fmt.Println("Yellow Color")
//set to red
_, _, _ = setConsoleTextAttributeProc.Call(uintptr(handle), uintptr(FOREGROUND_RED), 0)
fmt.Println("Red Color")
//set to original
_, _, _ = setConsoleTextAttributeProc.Call(uintptr(handle), uintptr(consoleInfo.Attributes), 0)
}
view raw test.go hosted with ❤ by GitHub

Native iOS & Android MQTT Sample Code Demo (IoT)

 

Titik Programming Language V2 Update (Execute Complex Expression With RPN And Shunting-yard Algo)