本文整理汇总了Python中connection.Connection.send方法的典型用法代码示例。如果您正苦于以下问题:Python Connection.send方法的具体用法?Python Connection.send怎么用?Python Connection.send使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类connection.Connection
的用法示例。
在下文中一共展示了Connection.send方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __init__
# 需要导入模块: from connection import Connection [as 别名]
# 或者: from connection.Connection import send [as 别名]
class Client:
def __init__(self, socket, address, port):
print 'Init Client'
ee = EventEmitter()
self._packet_sender = PacketSender(socket, address, port)
self._connection = Connection(self._packet_sender)
@self._connection.ee.on('data')
def on_data(data):
ee.emit('data', data)
def on_message(message, rinfo):
if rinfo.address is not address or rinfo.port is not port:
return
packet = Packet(message)
if packet.getIsFinish():
socket.close()
return
self._connection.receive(packet)
#socket.on('message', on_message)
def send(self, data):
self._connection.send(data)
def close(self):
self._packet_sender.send(Packet.createFinishPacket())
示例2: ClientApplication
# 需要导入模块: from connection import Connection [as 别名]
# 或者: from connection.Connection import send [as 别名]
class ClientApplication(object):
'''
Used for testing the methods that will be available via the RTP-3251 API
'''
def __init__(self):
pass
#Client commands
def connect(self, portOfClient=12000, destIp="143.215.129.100", destPort=7000):
#Command: connect (only for projects that support bi-directional transfers)
#The FTA-client connects to the FTA-server (running at the same IP host).
self.clientConnection = Connection()
self.clientConnection.open(portOfClient, (destIp, destPort))
def getF(self, fileName):
#Command: get F (only for projects that support bi-directional transfers)
#The FTA-client downloads file F from the server (if F exists in the same directory as the fta-server executable).
fileRequestObj = ['FFFFFFFF', fileName]
self.clientConnection.send(pickle.dumps(fileRequestObj))
serialObj = None
while(serialObj == None):
serialObj = self.clientConnection.receive()
fullfilledRequest = pickle.loads(serialObj)
if (fullfilledRequest[0] == fileName+"FromServer"): #write the contents (i.e. the second item in the object array
f = open(fileName+"FromServer", "w")
# file_path = path.relpath("clientFiles/"+fileName)
f.write(fullfilledRequest[1])
f.close()
print ("Client successfully received", fileName+"FromServer")
else:
print ("Client received", fullfilledRequest[0], "but was expecting", fileName+"FromServer")
def postF(self, fileName):
#Command: post F (only for projects that support bi-directional transfers)
#The FTA-client uploads file F to the server (if F exists in the same directory as the fta-client executable).
f = open(fileName, 'r')
obj = [fileName+"AtServer", f.read()]
f.close()
self.clientConnection.send(pickle.dumps(obj))
serialObj = None
while(serialObj == None):
serialObj = self.clientConnection.receive()
serverReply = pickle.loads(serialObj)
if (serverReply[0] == fileName+"AtServer" and serverReply[1] == "confirmed"):
print (fileName + " was confirmed")
else:
print (fileName + " was not confirmed!")
def terminate(self):
#Command: disconnect (only for projects that support bi-directional transfers)
#The FTA-client terminates gracefully from the FTA-server.
self.clientConnection.terminate()
示例3: Bot
# 需要导入模块: from connection import Connection [as 别名]
# 或者: from connection.Connection import send [as 别名]
class Bot(object):
ping_pattern = re.compile('^PING (?P<payload>.*)')
chanmsg_pattern = re.compile(':(?P<nick>.*?)!\S+\s+?PRIVMSG\s+#(?P<channel>[-\w]+)\s+:(?P<message>[^\n\r]+)')
def __init__(self, server, ident, channel, path):
self._dispatch_table = (
(self.ping_pattern, self.handle_ping),
(self.chanmsg_pattern, self.handle_chanmsg))
self._logger = Logging(path)
self.server = server
self.ident = ident
self.channel = channel
self.start()
def start(self):
self._connection = Connection(self.server)
self.register_connection(self.ident)
self.join_channel(self.channel)
def loop(self):
while True:
try:
line = self._connection.read()
except socket.error as se:
trackeback.print_exc()
print "Caught exception. Will reconnect."
del(self._connection)
time.sleep(60)
self.start()
continue
for pattern, handler in self._dispatch_table:
match = pattern.match(line)
if match:
handler(**match.groupdict())
def handle_ping(self, payload):
self._connection.send("PONG " + payload)
def handle_chanmsg(self, nick, channel, message):
self._logger.write(nick + ": " + message)
def register_connection(self, ident):
nick, passw = ident
self._connection.send("PASS " + passw)
self._connection.send("NICK " + nick)
self._connection.send("USER " + nick + " 0 * :" + nick)
def join_channel(self, channel):
chan, passw = channel
self._connection.send("JOIN " + chan + " " + passw)
示例4: send_sms
# 需要导入模块: from connection import Connection [as 别名]
# 或者: from connection.Connection import send [as 别名]
def send_sms(to, signature, text, userid, key):
"""Fast function for sending sms.
Create connection with given (userid, key) pair and
send sms.
:note: Your @signature must be verified on bytehand.
:param to: receiver phone number.
:param signature: value of "from"-field of sms message.
:param text: message content.
:param userid: your bytehand api id.
:param key: your bytehand api key.
:see: https://www.bytehand.com/secure/settings to get your key and id.
"""
to = str(to)
userid = str(userid)
if not to.isdigit():
raise TypeError('Incorrect "to"-field format. '
'It must be string of digits, '
'but it is: "{}"'.format(to))
if not text:
raise TypeError('Can\'t send empty message.')
if not signature:
raise TypeError('Signature should be set.')
if not userid.isdigit():
raise TypeError('User id must be digit, '
'but it is: {}'.format(userid))
conn = Connection(userid=userid, key=key)
return conn.send(to=to, signature=signature, text=text)
示例5: ServerApplication
# 需要导入模块: from connection import Connection [as 别名]
# 或者: from connection.Connection import send [as 别名]
class ServerApplication():
'''
Used for testing the methods that will be available via the RTP-3251 API
'''
def __init__(self, _debug=False):
self._debug = _debug
pass
def openServer(self, portOfServer=12001):
self.serverConnection = Connection(self._debug)
self.serverConnection.open(portOfServer)
def listen(self):
while(1):
serialObj = None
while(serialObj == None):
serialObj = self.serverConnection.receive() #stuck until receives a file read or write request
requestObj = pickle.loads(serialObj)
if (requestObj[0] == "FFFFFFFF"): #client wants file
self.replyF(requestObj[1])
else: #client is posting file as ['filename', content]
f = open(requestObj[0],'w')
f.write(requestObj[1])
f.close()
fileConfirmation = [requestObj[0], 'confirmed']
self.serverConnection.send(pickle.dumps(fileConfirmation))
def replyF(self, fileName):
#Command: post F (only for projects that support bi-directional transfers)
#The FTA-client uploads file F to the server (if F exists in the same directory as the fta-client executable).
f = open(fileName, 'r')
obj = [fileName+"FromServer", f.read()]
f.close()
self.serverConnection.send(pickle.dumps(obj))
def terminate(self):
#Shuts down FTA-Server gracefully
self.serverConnection.terminate()
示例6: Client
# 需要导入模块: from connection import Connection [as 别名]
# 或者: from connection.Connection import send [as 别名]
class Client(Listener):
def __init__(self):
Listener.__init__(self)
self.parser = Parser()
self.connection = Connection()
self.connection.add_listener("readline", self.readline_handler)
self.connection.add_listener("connect", self.connect_handler)
self.connection.add_listener("disconnect", self.disconnect_handler)
self.connection.connect()
def connect_handler(self, event):
self.add_listener("ping", self.ping_handler)
event.connection.send("NICK foo")
event.connection.send("USER foo 0 * :foo")
self.add_listener("welcome", self.ready_handler)
self.add_listener("privmsg", self.message_handler)
# TODO
# Make it as AutoJoinPlugin
def join(self, channel):
self.connection.send("JOIN " + channel)
def message_handler(self, event):
print "--" + event.message + "--"
if event.message == "quit":
self.connection.send("QUIT")
self.connection.send("PRIVMSG " + event.channel + " :" + event.message)
def ready_handler(self, event):
self.join("#foo")
# TODO
# Make it as PingPlugin
def ping_handler(self, event):
event.connection.send("PONG " + event.data)
def disconnect_handler(self, event):
print self
def readline_handler(self, event):
e = self.parser.parse(event)
#print event.data
if e:
self.dispatch(e)
示例7: __init__
# 需要导入模块: from connection import Connection [as 别名]
# 或者: from connection.Connection import send [as 别名]
class Minecraft:
"""The main class to interact with a running instance of Minecraft Pi."""
def __init__(self, connection=None, autoId=True):
if connection:
self.conn = connection
else:
self.conn = Connection()
if security.AUTHENTICATION_USERNAME and security.AUTHENTICATION_PASSWORD:
self.conn.authenticate(security.AUTHENTICATION_USERNAME, security.AUTHENTICATION_PASSWORD)
self.camera = CmdCamera(self.conn)
self.entity = CmdEntity(self.conn)
self.playerId = None
if autoId:
try:
self.playerId = int(environ['MINECRAFT_PLAYER_ID'])
self.player = CmdPlayer(self.conn,playerId=self.playerId)
except:
try:
self.playerId = self.getPlayerId(environ['MINECRAFT_PLAYER_NAME'])
self.player = CmdPlayer(self.conn,playerId=self.playerId)
except:
if security.AUTHENTICATION_USERNAME:
try:
self.playerId = self.getPlayerId(security.AUTHENTICATION_USERNAME)
self.player = CmdPlayer(self.conn,playerId=self.playerId)
except:
self.player = CmdPlayer(self.conn)
else:
self.player = CmdPlayer(self.conn)
else:
self.player = CmdPlayer(self.conn)
self.events = CmdEvents(self.conn)
self.enabledNBT = False
def spawnEntity(self, *args):
"""Spawn entity (type,x,y,z,tags) and get its id => id:int"""
return int(self.conn.sendReceive("world.spawnEntity", args))
def removeEntity(self, *args):
"""Remove entity (id)"""
self.conn.send("world.removeEntity", args)
def getBlock(self, *args):
"""Get block (x,y,z) => id:int"""
return int(self.conn.sendReceive_flat("world.getBlock", floorFlatten(args)))
def getBlockWithData(self, *args):
"""Get block with data (x,y,z) => Block"""
ans = self.conn.sendReceive_flat("world.getBlockWithData", floorFlatten(args))
return Block(*map(int, ans.split(",")[:2]))
def getBlockWithNBT(self, *args):
"""
Get block with data and nbt (x,y,z) => Block (if no NBT) or (Block,nbt)
For this to work, you first need to do setting("include_nbt_with_data",1)
"""
if not self.enabledNBT:
self.setting("include_nbt_with_data",1)
self.enabledNBT = True
try:
ans = self.conn.sendReceive_flat("world.getBlockWithData", floorFlatten(args))
except RequestError:
# retry in case we had a Fail from the setting
ans = self.conn.receive()
else:
ans = self.conn.sendReceive_flat("world.getBlockWithData", floorFlatten(args))
return stringToBlockWithNBT(ans)
"""
@TODO
"""
def fallbackGetCuboid(self, getBlock, *args):
(x0,y0,z0,x1,y1,z1) = map(lambda x:int(math.floor(float(x))), flatten(args))
out = []
for y in range(min(y0,y1),max(y0,y1)+1):
for x in range(min(x0,x1),max(x0,x1)+1):
for z in range(min(z0,z1),max(z0,z1)+1):
out.append(getBlock(x,y,z))
return out
def fallbackGetBlocksWithData(self, *args):
return self.fallbackGetCuboid(self.getBlockWithData, args)
def fallbackGetBlocks(self, *args):
return self.fallbackGetCuboid(self.getBlock, args)
def fallbackGetBlocksWithNBT(self, *args):
return self.fallbackGetCuboid(self.getBlockWithNBT, args)
def getBlocks(self, *args):
"""
Get a cuboid of blocks (x0,y0,z0,x1,y1,z1) => [id:int]
Packed with a y-loop, x-loop, z-loop, in this order.
#.........这里部分代码省略.........
示例8: Node
# 需要导入模块: from connection import Connection [as 别名]
# 或者: from connection.Connection import send [as 别名]
class Node(object):
def __init__(self, syncObj, nodeAddr):
self.__syncObj = weakref.ref(syncObj)
self.__nodeAddr = nodeAddr
self.__ip = syncObj._getResolver().resolve(nodeAddr.split(':')[0])
self.__port = int(nodeAddr.split(':')[1])
self.__poller = syncObj._getPoller()
self.__conn = Connection(socket=None, timeout=syncObj._getConf().connectionTimeout)
self.__shouldConnect = syncObj._getSelfNodeAddr() > nodeAddr
self.__lastConnectAttemptTime = 0
self.__lastPingTime = 0
self.__status = NODE_STATUS.DISCONNECTED
def __del__(self):
self.__conn = None
self.__poller = None
def onPartnerConnected(self, conn):
self.__conn = conn
self.__status = NODE_STATUS.CONNECTED
self.__poller.subscribe(self.__conn.fileno(),
self.__processConnection,
POLL_EVENT_TYPE.READ | POLL_EVENT_TYPE.WRITE | POLL_EVENT_TYPE.ERROR)
def getStatus(self):
return self.__status
def isConnected(self):
return self.__status == NODE_STATUS.CONNECTED
def getAddress(self):
return self.__nodeAddr
def getSendBufferSize(self):
return self.__conn.getSendBufferSize()
def send(self, message):
if self.__status != NODE_STATUS.CONNECTED:
return False
self.__conn.send(message)
if self.__conn.isDisconnected():
self.__status = NODE_STATUS.DISCONNECTED
self.__poller.unsubscribe(self.__conn.fileno())
self.__conn.close()
return False
return True
def connectIfRequired(self):
if not self.__shouldConnect:
return
if self.__status != NODE_STATUS.DISCONNECTED:
return
if time.time() - self.__lastConnectAttemptTime < self.__syncObj()._getConf().connectionRetryTime:
return
self.__status = NODE_STATUS.CONNECTING
self.__lastConnectAttemptTime = time.time()
if not self.__conn.connect(self.__ip, self.__port):
self.__status = NODE_STATUS.DISCONNECTED
return
self.__poller.subscribe(self.__conn.fileno(),
self.__processConnection,
POLL_EVENT_TYPE.READ | POLL_EVENT_TYPE.WRITE | POLL_EVENT_TYPE.ERROR)
def __processConnection(self, descr, eventType):
if descr != self.__conn.fileno():
self.__poller.unsubscribe(descr)
return
isError = False
if eventType & POLL_EVENT_TYPE.ERROR:
isError = True
if eventType & POLL_EVENT_TYPE.READ or eventType & POLL_EVENT_TYPE.WRITE:
if self.__conn.socket().getsockopt(socket.SOL_SOCKET, socket.SO_ERROR):
isError = True
else:
if self.__status == NODE_STATUS.CONNECTING:
self.__conn.send(self.__syncObj()._getSelfNodeAddr())
self.__status = NODE_STATUS.CONNECTED
if isError or self.__conn.isDisconnected():
self.__status = NODE_STATUS.DISCONNECTED
self.__conn.close()
self.__poller.unsubscribe(descr)
return
if eventType & POLL_EVENT_TYPE.WRITE:
if self.__status == NODE_STATUS.CONNECTING:
self.__conn.send(self.__syncObj()._getSelfNodeAddr())
self.__status = NODE_STATUS.CONNECTED
self.__conn.trySendBuffer()
event = POLL_EVENT_TYPE.READ | POLL_EVENT_TYPE.ERROR
if self.__conn.getSendBufferSize() > 0:
event |= POLL_EVENT_TYPE.WRITE
if not self.__conn.isDisconnected():
self.__poller.subscribe(descr, self.__processConnection, event)
if eventType & POLL_EVENT_TYPE.READ:
if self.__conn.read():
#.........这里部分代码省略.........
示例9: Connection
# 需要导入模块: from connection import Connection [as 别名]
# 或者: from connection.Connection import send [as 别名]
'''_
@author: Curtis Yu
@contact: [email protected]
@since: 2/18/16
'''
# For test only
import time
from connection import Connection
if __name__ == "__main__":
con = Connection("10.66.4.82", 52000, 'UDP')
con.send('still alive')
time.sleep(2)
con.send('still alive')
con.close()
示例10: fatal
# 需要导入模块: from connection import Connection [as 别名]
# 或者: from connection.Connection import send [as 别名]
method = args[0]
uri = args[1]
if max_pages is not None and method != 'GET':
fatal('--max-pages is only supported with method GET')
params = {}
for arg in args[2:]:
key, val = arg.split('=')
params[key] = val
token = os.environ.get('OCTOHUB_TOKEN', None)
endpoint = os.environ.get('OCTOHUB_ENDPOINT', None)
conn = Connection(token, endpoint)
try:
if max_pages is None:
response = conn.send(method, uri, params, data)
print json.dumps(response.parsed, indent=1)
else:
parsed = []
pager = Pager(conn, uri, params, max_pages=max_pages)
for response in pager:
parsed.extend(response.parsed)
print json.dumps(parsed, indent=1),
except ResponseError, e:
fatal(e)
if __name__ == '__main__':
main()
示例11: search_client
# 需要导入模块: from connection import Connection [as 别名]
# 或者: from connection.Connection import send [as 别名]
class search_client():
def __init__(self): # Initializes to default values all configuration variables and other objects required for the functioning of this system.
self._download = {} # Container for download manager thread and status variables
self._config = {} # This dictionary will store all the configuration variables that will subsequently be used by this client.
self._dir = {} # Application Directory Locations
self._step = {} # Application Directory Locations
self.active = False
self._config["hubcount"] = "0/1/0"
# debug files
self._debug_fh = open("debug-log.txt","w+")
with open('search.csv', 'a+') as output_csvfile:
fieldnames = ['date', 'ip', 'search_query']
csv_writer = csv.DictWriter(output_csvfile, fieldnames=fieldnames, delimiter=',')
csv_writer.writeheader()
# User Details
self._config["nick"] = "Anonymous" # User Nickname
self._config["pass"] = "" # User Password
self._config["status"] = 1 # User Status
self._config["desc"] = "" # User Description
self._config["email"] = "" # User EMail Address
self._config["sharesize"] = 0 # Total size of data shared by the user in bytes
self._config["operator"] = False # Whether or not this user is an operator on the hub
# Client Details
self._config["client"] = "pyDC" # Client Name
self._config["version"] = "1" # Client Version
self._config["connection"] = "100" # Connection Speed Indicator (Mbps)
self._config["mode"] = True # Whether or not this client can act as a server for peer-to-peer transfers.
self._config["cid"] = "%10d" % (random.randint(0,10**10-1)) # Client ID : CID needs to be pseudorandomly generated with negligible collision probability
self._config["localhost"] = socket.gethostbyname(socket.gethostname()) # The IP Address of this system
self._config["group_base"] = "general" # The name of the default group to which an unclassfied nick belongs to.
self._config["filelist"] = "files.xml.bz2" # The identifier of filelists in _queue
self._config["savedata"] = "configuration.dat" # The same of the file in which data will be saved
self._config["sr_count"] = 10 # Maximum number of search results to return per request
# Hub Details
self._config["host"] = "10.109.49.49" # The address of the hub to which we want to connect
self._config["port"] = 411 # The port at which the intended hub is running
self._config["hubname"] = "" # The name of the hub to which you connect
self._config["topic"] = "" # The topic of the hub to which you connect
# Connection Details
self._config["searchtime_manual"] = 15 # The time in seconds for which a user-initiated search is waiting for more results
self._config["searchtime_auto"] = 5 # The time in seconds for which an automatic search for TTH alternates is waiting for results
self._config["retry"] = 3 # Number of times a connection request will be sent to a remote host if it isnt responding
self._config["wait"] = 5 # Number of seconds to wait between sending repeated connection requests.
# Negotionation Details
self._config["lock"] = "Majestic12" # A random string used during authentication
self._config["key"] = self.lock2key(self._config["lock"]) # Generated using the above lock used during authorization
self._config["signature"] = "SourceCode" # A random string used during negotiation, conventionally used to indicate client name
self._config["support"] = "XmlBZList ADCGet TTHF" # The set of protocols that this client supports (space separated). More options: MiniSlots, TTHL, ZLIG
# Transfer Control
self._download["upslots"] = 0 # The number of upload slots currently in use
self._download["maxupslots"] = 3 # The maximum number of upload slots possible
self._download["downslots"] = 0 # The number of download slots currently in use
self._download["maxdownslots"] = 5 # The maximum number of download slots possible
# Step Control
self._config["step_time"] = 1 # How long the step functions waits before each run
self._step["active"] = False # Whether or not the step function is running
self._step["thread"] = None # The thread pointing to the step function
self._step["function"] = None # The function to be called at every step run
self._step["args"] = None # Arguments that are provided to and returned by every call of the ste function.
# Download Manager
self._config["segment_size"] = 1024*1024*10 # 100MB : Size of blocks to be downloaded from different users
self._config["download_time"] = 1 # How long the step functions waits before each run
self._download["active"] = False # Whether the download manager is running
self._download["thread"] = None # The thread pointing to the download manager function
# self._download["lock"] = threading.Semaphore() # A lock used to ensure that only one download is being inititated at a time.
self._config["overwrite"] = False # Whether or not to overwrite existing files with the same name after download.
# Default Streams/Connections
self._mainchat = self._debug_fh.write #open("debug-mainchat.txt","w").write #sys.stdout # The function to which mainchat messages are sent
self._pm = None # The function to which mainchat messages are sent
self._debug = None # The function to which debug information is to be printed to. Do not use unless actually necessary.
self._socket = None # A connection to the Hub
# Persistant Data Structires, except _config
self._queue = [] # A list containing pseudo-objects of the format: {id,part,parts,type,nick,offset,length,priority,name,size,location,active}
self._userips = {} # Used to keep track of the IP addresses of users, even if they arent available. Given the more persistant nature of this dictionary, it is rather useful in determining the nickname, given the IP.
self._groups = { self._config["group_base"]:[] } # A dict of lists, key = groupname, list values = members
self._filelist = { self._config["group_base"]:[] } # A dict containing group->list_of_dirs_to_be_shared entries. Entries here need to be shared yet.
# Temporary Data Structures
self._nicklist = {} # A list of all nicknames connected to this hub
self._search = {} # A dict containing pointers to search pseudo-objects of the format: socket (a connection type object that sets up a UDP server on which to recieve search results), result (the stream to which results are sent upon arrival), mode (manual or auto)
self._transfer = [] # A list containing pointers to transfer pseudo-objects of the format: {host,port,mode(active/passive),connection}
# self._shared = { self._config["group_base"]: xml.dom.minidom.Document() } # A xml.dom object containing the files and folders currently shared.
def connect(self): # Connects to the hub.
self.debug("Attempting to connect to Hub ...")
# if not self._config["ready"]: return self
self._socket = Connection({ "name":"DC Hub", "host":self._config["host"], "port":self._config["port"], "type":"tcp", "role":"client", "handler":self.server_handler, "args":{"buffer":""}, "debug":self._debug })
self.debug("Connected to Hub.")
return self
def server_handler(self,data,info,args): # Interacts with the DC, responding to any commands that are sent by it.
if data is None:
if "buffer" not in args: args = {"buffer":""}
return args
args["buffer"]+=data
#.........这里部分代码省略.........
示例12: __init__
# 需要导入模块: from connection import Connection [as 别名]
# 或者: from connection.Connection import send [as 别名]
class Bot:
def __init__(self, config):
self.config = config
self.state = STATE.DISCONNECTED
self.conn = None
self.last_recv = None
self.awaiting_pong = False
self.handlers = {
'PING': self.handle_ping,
'376': self.handle_motd, # RPL_ENDOFMOTD
'422': self.handle_motd, # ERR_NOMOTD
'NOTICE': self.handle_notice,
'MODE': self.handle_mode,
'PRIVMSG': self.handle_privmsg,
}
self.scripts = defaultdict(list)
def __str__(self):
return '<Bot: %s/%s>' % (self.config.host, self.config.nick)
def exception(self, line):
exc_type, exc_value, exc_tb = sys.exc_info()
exc_list = traceback.format_exception(exc_type, exc_value, exc_tb)
self.log(line + '\n' + ''.join(exc_list))
path, lineno, method, code = traceback.extract_tb(exc_tb)[-1]
path = os.path.relpath(path)
exc_name = exc_type.__name__
notice = '%s:%s():%d %s: %s' % (path, method, lineno, exc_name, exc_value)
if code is not None:
notice += ' | ' + code[:50]
self.notice(config.settings['owner'], notice)
def log(self, text):
log.write('%s/%s: %s' % (self.config.host, self.config.nick, text))
def connect(self):
host = self.config.host
port = self.config.port
self.log('connecting to port %d...' % port)
self.last_recv = time.time()
self.awaiting_pong = False
if not self.conn:
self.conn = Connection()
fd, error = self.conn.connect(host, port)
if error:
self.log(error)
self.state = STATE.DISCONNECTED
else:
self.state = STATE.CONNECTING
self.handle_notice(None)
return fd
def handle(self):
for line in self.conn.recv():
msg = ServerMessage(line)
handler = self.handlers.get(msg.command)
if handler:
try:
handler(msg)
except:
self.exception(line)
self.last_recv = time.time()
def check_disconnect(self, ts):
time_since = ts - self.last_recv
ping_timeout_wait = config.PING_INTERVAL + config.PING_TIMEOUT
if time_since > ping_timeout_wait:
self.log('no reply from server in %ds' % ping_timeout_wait)
self.disconnect()
return True
elif time_since > config.PING_INTERVAL and not self.awaiting_pong and self.state == STATE.IDENTIFIED:
# don't let the server's reply to ping reset last_recv unless we're fully
# identified lest we get stuck forever in a partially-connected state
self.ping()
def nick(self, new_nick):
self.conn.send('nick', new_nick)
def join(self, channel):
self.conn.send('JOIN', channel)
def part(self, channel):
self.conn.send('PART', channel)
def say(self, target, message):
self.conn.send('PRIVMSG', target, ':'+message)
def notice(self, target, message):
self.conn.send('NOTICE', target, ':'+message)
def ctcp_reply(self, target, *args):
self.notice(target, '%c%s%c' % (1, ' '.join(args), 1))
def ping(self):
self.conn.send('PING', 'pbot')
self.awaiting_pong = True
#.........这里部分代码省略.........
示例13: OTRXMPPChannel
# 需要导入模块: from connection import Connection [as 别名]
# 或者: from connection.Connection import send [as 别名]
class OTRXMPPChannel(object):
"""
OTR-XMPP communications channel
-------------------------------
Uses Off-the-Record Messaging for communications with XMPP destinations
See https://otr.cypherpunks.ca/
Example::
import time
from otrxmppchannel import OTRXMPPChannel
from otrxmppchannel.connection import OTR_TRUSTED, OTR_UNTRUSTED,
OTR_UNENCRYPTED, OTR_UNKNOWN
privkey = open('.otrprivkey', 'r').read()
channel = OTRXMPPChannel(
'[email protected]/datadiode',
'supersecret',
[
(
'[email protected]',
'33eb6b01c97ceba92bd6b5e3777189c43f8d6f03'
),
'[email protected]'
],
privkey
)
def my_receive(msg, from_jid, otr_state):
state = ''
if otr_state == OTR_TRUSTED:
state = 'trusted'
elif otr_state == OTR_UNTRUSTED:
state = 'UNTRUSTED!'
elif otr_state == OTR_UNENCRYPTED:
state = 'UNENCRYPTED!'
else:
state = 'UNKNOWN OTR STATUS!'
print('received %s from %s (%s)' % (msg, from_jid, state))
channel.send('') # set up OTR
time.sleep(3)
channel.send('This message should be encrypted')
NOTE: XMPP invitations are not handled
NOTE: It seems to take roughly 3 seconds to set up an OTR session.
Messages sent before the session is ready may be lost.
:param jid: source JID, e.g. '[email protected]'
:param password: XMPP server password
:param recipients: a single recipient JID, a tuple of
*(jid, OTRFingerprint/None)*, or a list of same
:param privkey: base64-encoded DSA private key for OTR. If *None* is
passed, a new key will be generated and dumped via a *ValueError*
exception.
"""
def __init__(self, jid, password, recipients, privkey=None):
usage = 'recipients can be a single recipient JID, a tuple of ' \
'(jid, OTRFingerprint|None), or a list of same. Example: ' \
'[\'[email protected]\', ' \
'(\'[email protected]\', ' \
'\'43d36b01c67deba92bd6b5e3711189c43f8d6f04\')].'
# normalize recipients to a list of tuples
if isinstance(recipients, str):
self.recipients = [(recipients, None)]
elif isinstance(recipients, tuple):
self.recipients = [recipients]
elif isinstance(recipients, list):
self.recipients = recipients
else:
raise TypeError(usage)
for i in range(0, len(self.recipients) - 1):
if isinstance(self.recipients[i], str):
self.recipients[i] = self.recipients[i], None
elif isinstance(self.recipients[i], tuple):
if len(self.recipients[i]) > 2 or len(self.recipients[i]) < 1:
raise TypeError(usage)
if len(self.recipients[i]) == 1:
self.recipients[i] = self.recipients[i], None
else:
raise TypeError(usage)
self.connection = Connection(jid, password, privkey, self.on_receive)
self.connection.start()
def send(self, message):
"""
Send *message* to recipients
:param message: message string
"""
for recipient in self.recipients:
self.connection.send(message, recipient)
def on_receive(self, message, from_jid, otr_state):
"""
Override this method to create a custom message receipt handler. The
handler provided simply discards received messages. Here is an
example::
from connection import OTR_TRUSTED, OTR_UNTRUSTED, OTR_UNENCRYPTED
#.........这里部分代码省略.........
示例14: RootDataRef
# 需要导入模块: from connection import Connection [as 别名]
# 或者: from connection.Connection import send [as 别名]
class RootDataRef(DataRef):
'''A reference to a root of a Firbase.'''
def __init__(self, url, ssl_options=None):
'''Construct a new Firebase reference from a full Firebase URL.'''
self.connection = Connection(url, self, ssl_options=ssl_options)
self.base_url = url
self.structure = Structure(self)
self.subscriptions = {}
self.history = []
self.connection.daemon = True
self.connection.start()
self._keep_alive()
atexit.register(self.close)
DataRef.__init__(self, self, '')
def _process(self, message):
'''Process a single incoming message'''
# This whole thing needs to be rewritten to use all the new information about the protocol
debug(message)
# If message type is data
if message['t'] == 'd':
data = message['d']
# If r is in data and set to 1 then it's probably a response
# to something we sent like a sub request or an auth token
if 'r' in data:
historical_entry = self.history[data['r']-1]
request = historical_entry['message']
callbacks = historical_entry['callbacks']
error = data['b']['s']
if error != 'ok':
if error == 'permission_denied':
path = request['d']['b']['p']
print 'FIREBASE WARNING: on() or once() for %s failed: %s' % (path, error)
elif error == 'expired_token' or error == 'invalid_token':
print 'FIREBASE WARNING: auth() failed: %s' % (error)
else:
path = request['d']['b']['p']
print 'FIREBASE WARNING: unknown for %s failed: %s' % (path, error)
onCancel = callbacks.get('onCancel', None)
if not onCancel is None:
onCancel(error)
onComplete = callbacks.get('onComplete', None)
if not onComplete is None:
onComplete(error if error != 'ok' else None)
# If t is in data then it's the response to the initial connection, maybe
elif 't' in data:
pass
# If a is in data, it's a new data blob for a node, maybe
elif 'a' in data:
if data['a'] == 'c':
# This type of message is created when we lose permission to read
# and it requires some extra effort to implement as we call onCancel
# for all effected callbacks, which are any anscestors of the path
pass
else:
b_data = data['b']
path = b_data['p']
path_data = b_data['d']
self._store(path, path_data)
# If message type is... control?
if message['t'] == 'c':
pass
def _store(self, path, path_data):
'''Store a single path worth of data into the strucutre.'''
if not path or path[0] != "/":
path = "/%s" % path
self.structure.store(path, path_data)
def _send(self, message, callbacks=None):
'''Send a single message to Firebase.'''
historical_entry = {
'message': message,
'callbacks': {} if callbacks is None else callbacks
}
self.history.append(historical_entry)
message['d']['r'] = len(self.history)
self.connection.send(message)
def _subscribe(self, path, query, callbacks=None):
'''Subscribe to updates regarding a path'''
isSubscribed = self._is_subscribed(path, query)
# A subscription (listen) request takes two main arguments, p (path) and q (query).
if not isSubscribed:
#.........这里部分代码省略.........
示例15: print
# 需要导入模块: from connection import Connection [as 别名]
# 或者: from connection.Connection import send [as 别名]
try:
bot.getService(service_name).onDestroy(bot)
except AttributeError:
# Don't worry about it since this is optional
pass
sys.exit()
# Register signal handler for ctrl-c to allow bot services to know about their
# impending doom.
signal.signal(signal.SIGINT, SignalHandler)
# Implement the "bot" mainloop
while True:
try:
data = bot.recv()
print(data)
except UnicodeDecodeError:
print("Some unicode!!")
# Stay alive
if data.startswith("PING"):
bot.send("PONG " + data.split()[1])
else:
# TODO: Might be better to put the listeners in their own group apart
# from the "bot".
for m in Message.parse(data):
bot.processListeners(m)