本文整理汇总了Python中messenger.Messenger类的典型用法代码示例。如果您正苦于以下问题:Python Messenger类的具体用法?Python Messenger怎么用?Python Messenger使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Messenger类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: __init__
def __init__(self, appkey, alias, customid, topic, transfer, zigbee_addr):
self.__logger = logging.getLogger('zigbee_coordinator.Proxy')
self.__logger.debug('init')
Messenger.__init__(self, appkey, alias, customid)
self.transfer = transfer
self.topic = topic
self.zigbee_addr = zigbee_addr
开发者ID:yunbademo,项目名称:yunba-smartoffice,代码行数:7,代码来源:zigbee_coordinator.py
示例2: messenger_thread
class messenger_thread(Thread):
def __init__(self, irc_connection):
self.messenger = Messenger(irc_connection)
Thread.__init__(self)
def run(self):
self.messenger.run_loop()
开发者ID:rwgeaston,项目名称:silly-IRC-bots,代码行数:7,代码来源:generic_bot.py
示例3: __init__
def __init__(self, appkey, alias, customid, gpio_num):
self.__logger = logging.getLogger('power_plug.PowerPlug')
self.__logger.debug('init')
Messenger.__init__(self, appkey, alias, customid)
self.gpio_num = gpio_num
GPIO.setup(self.gpio_num, GPIO.OUT)
开发者ID:pengwj,项目名称:yunba-smartoffice,代码行数:7,代码来源:power_plug.py
示例4: start
def start(self, resource):
"""Creates Slack Web and RTM clients for the given Resource
using the provided API tokens and configuration, then
connects websocket and listens for RTM events.
Args:
resource (dict of Resource JSON): See message payloads:
https://beepboophq.com/docs/article/resourcer-api
"""
logger.info('Starting bot for resource: {}'.format(resource))
if ('resource' in resource and
'SlackBotAccessToken' in resource['resource']):
res_access_token = resource['resource']['SlackBotAccessToken']
self.clients = SlackClients(res_access_token)
if self.clients.rtm.rtm_connect():
logging.info(
u'Connected {} to {} team at https://{}.slack.com'.format(
self.clients.rtm.server.username,
self.clients.rtm.server.login_data['team']['name'],
self.clients.rtm.server.domain
)
)
msg_writer = Messenger(self.clients)
# Random markov here
markov_chain = Markov(3, msg_writer)
config_manager.start_config_loader()
event_handler = RtmEventHandler(
self.clients, msg_writer, markov_chain
)
time_event_handler = TimeTriggeredEventManager(
self.clients, msg_writer, markov_chain
)
os.chmod('./scripts/make_config.sh', 0755)
while self.keep_running:
for event in self.clients.rtm.rtm_read():
try:
event_handler.handle(event)
except:
err_msg = traceback.format_exc()
logging.error('Unexpected error: {}'.format(err_msg))
msg_writer.write_error(err_msg, event['channel'])
continue
self._auto_ping(time_event_handler)
time.sleep(.1)
else:
logger.error(
'Failed to connect to RTM client with token: {}'.format(
self.clients.token
)
)
开发者ID:ianadmu,项目名称:starter-python-bot,代码行数:58,代码来源:slack_bot.py
示例5: client_thread
def client_thread(conn):
current_state = WAITING_TO_START_GAME
messenger = Messenger(conn)
while current_state is not GAME_OVER:
if current_state is WAITING_TO_START_GAME:
game = init_game(messenger)
current_state = WAITING_FOR_MOVE
elif current_state is WAITING_FOR_MOVE:
messenger.send( str (game.incorrect + game.correct) );
letter = messenger.read()
if game.already_guessed(letter):
reply = "You've already guessed %r." % letter
else:
game.guess_letter(letter)
reply = str(game)
if game.gameover:
current_state = WAITING_TO_PLAY_AGAIN
messenger.send(reply)
messenger.send(str(game.gameover))
elif current_state is WAITING_TO_PLAY_AGAIN:
play_again = messenger.read()
if play_again == "play":
current_state = WAITING_TO_START_GAME
elif play_again == "quit":
current_state = GAME_OVER
conn.close()
开发者ID:RealStyle12,项目名称:hangman,代码行数:28,代码来源:server.py
示例6: authenticate_as_client
def authenticate_as_client(self, session_socket):
# authenticates an external server connected via session_socket
iv = self.receive_iv(session_socket)
master_encrypter = Encrypter(self.master_key, iv)
m = Messenger(session_socket, master_encrypter, self.continueHandler)
client_challenge = genStr(CHALLENGE_LENGTH)
client_challenge_hash = str(create_key(client_challenge))
hash_len = len(client_challenge_hash)
secretA = generateAorB()
publicA = pow(g, secretA, p)
m.send(client_challenge + str(publicA))
response = m.recv()
while not response:
response = m.recv()
if response[:hash_len] != client_challenge_hash:
m.close()
raise Exception('client could not authenticate')
server_challenge_hash = str(create_key(response[hash_len:hash_len + CHALLENGE_LENGTH]))
m.send(server_challenge_hash)
public_b = int(response[hash_len + CHALLENGE_LENGTH:])
self.log.info('g^b mod p is {}'.format(public_b))
session_key = create_key(str(pow(public_b, secretA, p)))
self.log.info('Session key generated by the client is {}'.format(session_key))
session_encrypter = Encrypter(session_key, iv)
session_m = Messenger(session_socket, session_encrypter, self.continueHandler)
self._messenger = session_m
开发者ID:Anna-Gudimova,项目名称:CPEN-442,代码行数:33,代码来源:sessionmanager.py
示例7: check_schedule
def check_schedule(self, localtime):
client = Client()
for volume in client.get_volumes():
try:
self._check_volume_schedule(localtime, volume)
except:
error_msg = 'Scheduler failed to check volume schedule. %r' % {
'volume_id': volume.id
}
logger.exception(error_msg)
msg = Messenger(volume)
msg.send('%s\n\n%s' % (error_msg, traceback.format_exc()))
开发者ID:drivnal,项目名称:drivnal,代码行数:13,代码来源:scheduler.py
示例8: message_sender
def message_sender(self):
self.message_collector()
msg = "%d messages waiting to be sent" % len(self.waiting_messages)
log.info(msg)
print >>sys.stdout, msg
sent_list = []
for message in self.waiting_messages:
sender = Messenger([message])
sender.check_config("smsleopard")
sent_msg = sender.send_sms()[0]
sent_list.extend(sent_msg)
msg = "%d sent messages" % len(sent_list)
log.info(msg)
for sent in sent_list:
self.db.update_outbox(sent)
开发者ID:CBinyenya,项目名称:cmsserver,代码行数:15,代码来源:cron.py
示例9: __init__
def __init__(self, appkey, alias, customid, file, presence, like):
self.__logger = logging.getLogger('stat.Stat')
self.__logger.debug('init')
Messenger.__init__(self, appkey, alias, customid)
self.file = file
self.data = {}
self.data['presence'] = presence
self.data['like'] = like
if presence != 0 or like != 0:
self.write_data()
else:
self.read_data()
开发者ID:lichunjing,项目名称:yunba-live-video,代码行数:15,代码来源:stat.py
示例10: __init__
def __init__(self, name='alex', nevts=100, evtfreq=100):
""" Alex class
It is the main driver application
It has a list of algorithms that runs in sequence for a given number of events
It has a dictionary of services to be set into each algorithm
It has a dictionary with run information and event information (clean each event) to be set into in each alorithm
"""
self.name = name # name of the application
self.ievt = 0 # current number of event processed
self.nevts = nevts # number of events to run
self.evtfreq = evtfreq # frequency to print event number in log
self.counters = {}
self.algs = [] # list of algorithms to run
self.svcs = {} # dictionary with the services
# primordial msg service
self.msg = Messenger(name='msg')
self.addsvc(self.msg) # add msg service
# primordial request service (handle errrors, abort/end of job requets)
self.req = RequestSvc(name='req',al=self)
self.addsvc(self.req) # add request service
# event data service
self.evt = DataSvc(name='evt')
self.addsvc(self.evt) # add event data service
self.exports = ['msg','req','evt'] # services to export to algorithms
return
开发者ID:nextsw,项目名称:alex,代码行数:25,代码来源:alex.py
示例11: __init__
def __init__(self, secrets):
self.trade_params = secrets["tradeParameters"]
self.pause_params = secrets["pauseParameters"]
self.Bittrex = Bittrex(secrets)
self.Messenger = Messenger(secrets)
self.Database = Database()
开发者ID:ilya0,项目名称:Crypto-Trading-Bot,代码行数:7,代码来源:trader.py
示例12: start
def start(self, resource):
"""Creates Slack Web and RTM clients for the given Resource
using the provided API tokens and configuration, then connects websocket
and listens for RTM events.
Args:
resource (dict of Resource JSON): See message payloads - https://beepboophq.com/docs/article/resourcer-api
"""
logger.debug("Python Version: " + sys.version)
logging.info('Starting bot for resource: {}'.format(resource))
if 'resource' in resource and 'SlackBotAccessToken' in resource['resource']:
res_access_token = resource['resource']['SlackBotAccessToken']
self.clients = SlackClients(res_access_token)
if self.clients.rtm.rtm_connect():
logging.info(u'Connected {} to {} team at https://{}.slack.com'.format(
self.clients.rtm.server.username,
self.clients.rtm.server.login_data['team']['name'],
self.clients.rtm.server.domain))
msg_writer = Messenger(self.clients)
event_handler = RtmEventHandler(self.clients, msg_writer)
while self.keep_running:
for event in self.clients.rtm.rtm_read():
try:
event_handler.handle(event)
except:
err_msg = traceback.format_exc()
logging.error('Unexpected error: {}'.format(err_msg))
msg_writer.write_error(event['channel'], err_msg)
continue
self._auto_ping()
time.sleep(.1)
else:
logger.error('Failed to connect to RTM client with token: {}'.format(self.clients.token))
开发者ID:davenewham,项目名称:starter-python-bot,代码行数:39,代码来源:slack_bot.py
示例13: authenticate_as_server
def authenticate_as_server(self, session_socket):
# authenticates an external client connected via session_socket
iv = self.generate_and_send_iv(session_socket) # the server should generate a random iv
master_encrypter = Encrypter(self.master_key, iv)
m_messenger = Messenger(session_socket, master_encrypter, self.continueHandler)
secret_b = generateAorB()
public_b = str(pow(g, secret_b, p))
server_challenge = genStr(CHALLENGE_LENGTH)
server_challenge_hash = str(create_key(server_challenge))
response = m_messenger.recv()
while not response:
response = m_messenger.recv()
client_challenge = response[:CHALLENGE_LENGTH]
client_challenge_hash = str(create_key(client_challenge))
public_a = response[CHALLENGE_LENGTH:]
self.log.info('publicA is {}'.format(public_a))
m_messenger.send(client_challenge_hash + server_challenge + public_b)
session_key = create_key(str(pow(int(public_a), secret_b, p)))
self.log.info('session key is {}'.format(session_key))
response = m_messenger.recv()
while not response:
response = m_messenger.recv()
if response != server_challenge_hash:
self.log.warn('Client could not be authenticated. Session will be terminated!')
m_messenger.close()
else:
print('Server Authentication Successful!!!')
session_encrypter = Encrypter(session_key, iv)
self._messenger = Messenger(session_socket, session_encrypter, self.continueHandler)
开发者ID:Anna-Gudimova,项目名称:CPEN-442,代码行数:37,代码来源:sessionmanager.py
示例14: __init__
def __init__(self):
super().__init__()
self.connection = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.protocol("WM_DELETE_WINDOW", lambda: destroy_all(self.connection, self))
self.title("Chat Client")
self.length_struct = struct.Struct("!I")
self.messenger = Messenger(self.connection, self.length_struct)
self.username = ""
self.password = ""
self.connect = ConnectScreen(self, self.connect_to_server)
self.login = LoginScreen(self, self.check_data)
self.chat = ChatScreen(self, self.handle_out_going)
self.connect.pack()
self.connect.pack_children()
开发者ID:StaticFuzz,项目名称:PythonChat,代码行数:18,代码来源:client.py
示例15: __init__
def __init__(self):
super(Registry, self).__init__()
# Set up YAML parser for optional config file
self.config_path = path("cosmid.yaml")
self.config = ConfigReader(self.config_path)
# Extract stuff from config
self.email = self.config.find("email")
# Path to resource storage directory
self.directory = path(self.config.find("directory", default="resources"))
# Load history file consisting of already downloaded resources
self.history_path = path(self.directory + "/.cosmid.yaml")
self.history = HistoryReader(self.history_path)
# Set up a :class:`cosmid.messenger.Messenger`
self.messenger = Messenger("cosmid")
开发者ID:jrherr,项目名称:cosmid,代码行数:19,代码来源:core.py
示例16: _new_tube_cb
def _new_tube_cb(self, identifier, initiator, type, service, params, state):
_logger.debug('New tube: ID=%d initator=%d type=%d service=%s '
'params=%r state=%d' %(identifier, initiator, type,
service, params, state))
if (type == telepathy.TUBE_TYPE_DBUS and
service == SERVICE):
if state == telepathy.TUBE_STATE_LOCAL_PENDING:
self.tubes_chan[telepathy.CHANNEL_TYPE_TUBES].AcceptDBusTube(
identifier)
self.tube_conn = TubeConnection(self.conn,
self.tubes_chan[telepathy.CHANNEL_TYPE_TUBES],
identifier, group_iface = self.text_chan[
telepathy.CHANNEL_INTERFACE_GROUP])
_logger.debug('Tube created')
self.messenger = Messenger(self.tube_conn, self.initiating,
self.model)
开发者ID:lucian1900,项目名称:Webified,代码行数:19,代码来源:webactivity.py
示例17: make_socket
GAME_OVER = 5
def make_socket():
try:
c = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except socket.error, msg:
print "Client: Failed to create socket. Error code: " + str(msg[0]) \
+ ", Error message: " + msg[1]
sys.exit()
return c
if __name__ == "__main__":
sock = make_socket()
sock.connect((HOST,PORT))
messenger = Messenger(sock)
current_state = WAITING_FOR_WELCOME
while current_state is not GAME_OVER:
if current_state is WAITING_FOR_WELCOME:
print messenger.read()
current_state = WAITING_FOR_BOARD
elif current_state is WAITING_FOR_BOARD:
print messenger.read()
current_state = WAITING_FOR_GAME_STATUS
elif current_state is WAITING_FOR_GAME_STATUS:
msg = messenger.read()
if msg == "True":
current_state = WAITING_TO_PLAY_AGAIN
elif msg == "False":
current_state = WAITING_FOR_USER_INPUT
开发者ID:RealStyle12,项目名称:hangman,代码行数:31,代码来源:client.py
示例18: thread_client
def thread_client(conn, addr, db_conn, active_clients):
"""
Checks and verifies password/username, and handles adding new
users to the database.
Main client loop Accepts messages from client socket then
broadcasts message to all clients. If the connection is broken
the loop will break, database will be updated(active state).
:param conn: socket objected connected with remote client
:param addr: tuple of the remote clients address and port
:param db_conn: connection to the sqlite3 database containing user-info
"""
length_struct = struct.Struct("!I")
local_messenger = Messenger(conn, length_struct)
lock = _thread.allocate_lock()
verified = False # used to control looping
while not verified: # handle client login/signup credentials
try:
"""
first message received will be a login or sign up attempt
message_type will be "LOGIN" or "SIGNUP"
"""
message = local_messenger.recv()
message_type, username, password = message.split("`", 2)
except ValueError or ConnectionResetError:
print("bad connection at {}".format(addr))
break
# retrieve user info from database. username_check() returns two boolean values
lock.acquire()
username_exists, correct_password = username_check(db_conn, username, password)
lock.release()
# add new users to database
if message_type == "SIGNUP":
if username_exists: # username already taken
local_messenger.send("UNAVAILABLE")
else:
# acquire lock and add user to database and active_clients
lock.acquire()
new_user(db_conn, username, password)
active_clients[username] = conn
lock.release()
local_messenger.send("OK")
verified = True
# login existing users
elif message_type == "LOGIN":
if username_exists and correct_password:
if username not in active_clients: # username is not already signed in
# acquire lock and add username to active_clients
lock.acquire()
active_clients[username] = conn
lock.release()
local_messenger.send("OK")
verified = True
else:
local_messenger.send("USER_ACTIVE") # user is already active
else:
local_messenger.send("BAD") # wrong password or username
while verified:
"""
client will only be verified when an existing username and password have been
submitted, or a new username and password has been created.
verified loop will handle all incoming messages, errors, socket closures
"""
try:
message = local_messenger.recv()
except socket.error or struct.error:
print("bad connection at {}".format(addr))
break
if message:
lock.acquire()
local_messenger.broadcast(active_clients, message)
lock.release()
else:
# empty string signaling connection closed
lock.acquire()
del active_clients[username]
lock.release()
conn.close()
break
# clean up after client disconnects or the connection is broken
if username in active_clients:
lock.acquire()
del active_clients[username]
lock.release()
conn.close()
print("{} DISCONNECTED".format(addr))
开发者ID:StaticFuzz,项目名称:PythonChat,代码行数:98,代码来源:server.py
示例19: Messenger
#!/usr/bin/python
from messenger import Messenger
from os import getpid
messenger = Messenger('http://paxos.leedscodedojo.org.uk/live/a/gp-' + str(getpid()).zfill(5))
def sendMessage(msg):
print "Sending: " + str(msg)
messenger.postMessage(msg)
name = "brian"
lastAcceptedTimePeriod = 0
lastAcceptedValue = None
sentAccepted = False
lastPromisedTimePeriod = 0
while True:
currMessage = messenger.getNextMessage()
print "Received: " + str(currMessage)
timePeriod = currMessage['timePeriod']
if currMessage['type'] == 'prepare':
msg = {'type':'promised', 'timePeriod':timePeriod, 'by':name}
if not sentAccepted:
if timePeriod > lastPromisedTimePeriod:
lastPromisedTimePeriod = timePeriod
开发者ID:LeedsCodeDojo,项目名称:paxos-dojo,代码行数:30,代码来源:acceptor.py
示例20: __init__
class Manager:
"""
The middle-man of interaction between messenger and the SMS service.
"""
def __init__(self):
self.config = self.__load_config_file()
self.messenger = Messenger(self.config)
self.sms_service = SMSService()
def send_initial_greeting(self):
"""
Sends the initial SMS to new* patients at a pre-defined client time.
*New patients are those that have recently been added
to the clients database, which the service does not know.
Note: this is REQUIRED otherwise 'respond' & other services do not
function as database errors are thrown (understandably).
"""
from datetime import datetime
current_time = str(datetime.now().time())[0:5]
# Send the message to new patients at the defined time.
if current_time == self.config['initialQuestion']['time']:
for number in self.__new_patients():
message = self.messenger.initial_message()
self.sms_service.send(number, message)
self.__create_new_patient(number)
self.__save_message(number, message, 'sent')
def respond(self, patient_response):
"""
Respond to new SMS when it is received via a POST request.
Args:
patient_message (dict): Contains the number, and message sent to
the service by a patient.
Returns:
response (XML): twilio formatted response.
"""
number = patient_response['number']
patient_message = patient_response['message']
# Generate a reflective summary based on the patient's response.
summary = self.messenger.summary(patient_message)
# TODO: Fix this with the system set time (i.e. UTC)
midnight = int(datetime.today().strftime("%s")) - 24*60*60
# The number of questions sent since last night.
_questions = db.session.query(models.Message).filter(
models.Message.mobile == number,
models.Message.status == 'sent',
models.Message.timestamp >= midnight).all()
all_sent = [item.message for item in _questions]
# The number of OEQ sent since last night.
num_oeq = len([i for i in self.config['questions'] if i in all_sent])
print 'Number OEQ sent since last night was: %s' % str(num_oeq)
response = None
# Do not send a response if initial daily conversation not started.
if num_oeq >= 1:
print 'The last sms sent was: %s' % all_sent[-1]
if all_sent[-1] in self.config['questions']:
print 'Last message sent was an OEQ. Sending a RS to patient.'
response = summary
else:
print 'Inside the else..'
if (num_oeq >= int(self.config['limit'])): # True: OEQ >= LIMIT
print 'Inside the else... in the if...'
if self.config['endQuestion'] not in all_sent:
print 'Sending the conversation closer as limit met.'
response = self.config['endQuestion']
else:
print 'Message received was response to a RS. Sending OEQ.'
response = self.__select_question(number)
if response:
self.__save_message(number, patient_message, 'received')
self.__save_message(number, response, 'sent')
print 'The response (%s) has been saved to the database.' % response
return self.sms_service.reply(response)
else:
print 'No response was created.'
return '' # Prevents a 500 error code returned to POST.
def send_initial_question_to_all(self):
"""
Sends a question to all patients at a pre-defined day and time.
"""
known_patients = [item.mobile for item in
db.session.query(models.Patient.mobile).all()]
from datetime import datetime
print "Checking to see if open-ended question should be sent."
isDay = datetime.now().strftime("%A") in self.config["daysToSend"]
isTime = str(datetime.now().time())[0:5] == self.config["sendTime"]
if isDay and isTime:
for number in known_patients:
message = self.__select_question(number)
#.........这里部分代码省略.........
开发者ID:jawrainey,项目名称:sris,代码行数:101,代码来源:manager.py
注:本文中的messenger.Messenger类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论