Browse Source

Merge pull request #2 from isld/python-server

Python server
master
Blagovest Petrov 8 years ago
committed by GitHub
parent
commit
f41b7242b4
  1. 7
      server/config.py
  2. 18
      server/requirements.txt
  3. 135
      server/server.py

7
server/config.py

@ -0,0 +1,7 @@
twitter_conf = {
'TW_CONSUMER_KEY' : 'env',
'TW_CONSUMER_SECRET' : 'env',
'TW_ACCESS_TOKEN' : 'env',
'TW_ACCESS_TOKEN_SECRET' : 'env',
'TW_DEFAULT_TAG' : 'OpenFest2016',
}

18
server/requirements.txt

@ -0,0 +1,18 @@
colorama==0.3.7
eventlet==0.19.0
funcsigs==1.0.2
gevent==1.1.2
green==2.5.2
greenlet==0.4.10
logging==0.4.9.6
mock==2.0.0
oauthlib==2.0.0
pbr==1.10.0
pkg-resources==0.0.0
python-termstyle==0.1.10
requests==2.4.3
requests-oauthlib==0.4.1
six==1.7.3
telnetsrv==0.4
tweepy==3.2.0
Unidecode==0.4.19

135
server/server.py

@ -0,0 +1,135 @@
#!/usr/bin/python
import os, sys
import logging
import argparse
import eventlet
import tweepy
import config
import time
from telnetsrv.evtlet import TelnetHandler, command
for key in config.twitter_conf:
if config.twitter_conf[key] == 'env':
try:
os.environ[key]
config.twitter_conf[key] = os.environ[key]
except KeyError:
print "Please, set the environment variable %s or set it in the config" % key
sys.exit(1)
logging.getLogger('').setLevel(logging.DEBUG)
TELNET_IP_BINDING = '' #all
parser = argparse.ArgumentParser( description='Run a fttp server.')
parser.add_argument( 'port', metavar="PORT", type=int, help="The port on which to listen on." )
console_args = parser.parse_args()
TELNET_PORT_BINDING = console_args.port
class TwitterApi():
'''Twitter Api'''
auth = tweepy.OAuthHandler(config.twitter_conf['TW_CONSUMER_KEY'], config.twitter_conf['TW_CONSUMER_SECRET'])
auth.set_access_token(config.twitter_conf['TW_ACCESS_TOKEN'], config.twitter_conf['TW_ACCESS_TOKEN_SECRET'])
api = tweepy.API(auth)
def send(self, tweet):
self.api.update_status(tweet)
def get_tweets_by_tag(self, tag):
tweets = ""
feed = self.api.search(tag, count=20)
for i in feed:
tweets = tweets + i.text + "\n"
return tweets.encode('utf-8').strip()
class TestTelnetHandler(TelnetHandler):
# -- Override items to customize the server --
WELCOME = 'You have connected to the fttp server.'
PROMPT = "fttp% "
authNeedUser = False
authNeedPass = False
twitter = TwitterApi()
# queue = eventlet.queue.Queue(10000)
# wait = eventlet.semaphore.CappedSemaphore(1000)
def feed_auto(self):
# while True:
self.feed = self.twitter.get_tweets_by_tag(config.twitter_conf['TW_DEFAULT_TAG'])
self.writeresponse(self.feed)
# time.sleep(5)
def session_start(self):
'''Called after the user successfully logs in.'''
self.get_tweets_event = []
message = self.feed_auto()
event = eventlet.spawn(self.writemessage, message)
self.get_tweets_event.append(event)
def session_end(self):
'''Called after the user logs off.'''
for event in self.get_tweets_event:
event.kill()
def writeerror(self, text):
'''Called to write any error information (like a mistyped command).
Add a splash of color using ANSI to render the error text in red.
see http://en.wikipedia.org/wiki/ANSI_escape_code'''
TelnetHandler.writeerror(self, "\x1b[91m%s\x1b[0m" % text )
# -- Twitter Commands --
@command(['tweet', 'send'])
def command_tweet(self, params):
''' <message>
Sends the message as a tweet from @OpenFest_Fttp
'''
message = " ".join(params)
self.twitter.send(message)
@command(['feed', 'get_tweets'])
def command_get(self, params):
''' <#tag>
Gets latest tweets by a given tag (Default: #OpenFest2016)
'''
# if not params[0]:
# params[0] = "#OpenFest2016"
self.feed = self.twitter.get_tweets_by_tag(config.twitter_conf['TW_DEFAULT_TAG'])
self.writeresponse(self.feed)
if __name__ == '__main__':
Handler = TestTelnetHandler
class EvtletStreamServer(object):
def __init__(self, addr, handle):
self.ip = addr[0]
self.port = addr[1]
self.handle = handle
def serve_forever(self):
eventlet.serve(
eventlet.listen((self.ip, self.port)),
self.handle
)
# Multi-eventlet server
server = EvtletStreamServer(
(TELNET_IP_BINDING, TELNET_PORT_BINDING),
Handler.streamserver_handle
)
logging.info("Starting fttp server at port %d. (Ctrl-C to stop)" % (TELNET_PORT_BINDING) )
try:
server.serve_forever()
except KeyboardInterrupt:
logging.info("Server shut down.")
Loading…
Cancel
Save