<commit_before>import configparser
import os
from flask import Flask
from shopping_app.views import (IndexView, AddItemsView, DashboardView,
                                LoginView, Logout, RegisterView, RemoveShoppingList, ShoppingListDetail)

BASEDIR = os.path.dirname(os.path.abspath(__file__))

app = Flask(__name__)
config = configparser.ConfigParser()
config.read(BASEDIR + '/secret.ini')

# app urls
app.add_url_rule('/', view_func=IndexView.as_view('index'))
app.add_url_rule('/dashboard', view_func=DashboardView.as_view('dashboard'))
app.add_url_rule('/login', view_func=LoginView.as_view('login'))
app.add_url_rule('/logout', view_func=Logout.as_view('logout'))
app.add_url_rule('/register', view_func=RegisterView.as_view('register'))
app.add_url_rule('/create-shopping-list', view_func=AddItemsView.as_view('create-shopping-list'))
app.add_url_rule('/shopping-list-detail/', view_func=ShoppingListDetail.as_view('shopping-list-detail'))
app.add_url_rule('/remove-shopping-list', view_func=RemoveShoppingList.as_view('remove-shopping-list'))

# app conf

if __name__ == '__main__':
    app.run()
<commit_msg>Update main app url rules<commit_after>import configparser
import os
from flask import Flask
from shopping_app.views import (IndexView, AddItemsView, CreateShoppingList, DashboardView,
                                LoginView, Logout, RegisterView, RemoveShoppingList, ShoppingListDetail)

BASEDIR = os.path.dirname(os.path.abspath(__file__))

app = Flask(__name__)
config = configparser.ConfigParser()
config.read(BASEDIR + '/secret.ini')

# app urls
app.add_url_rule('/', view_func=IndexView.as_view('index'))
app.add_url_rule('/dashboard', view_func=DashboardView.as_view('dashboard'))
app.add_url_rule('/login', view_func=LoginView.as_view('login'))
app.add_url_rule('/logout', view_func=Logout.as_view('logout'))
app.add_url_rule('/register', view_func=RegisterView.as_view('register'))
app.add_url_rule('/create-shopping-list', view_func=CreateShoppingList.as_view('create-shopping-list'))
app.add_url_rule('/shopping-list-detail/', view_func=ShoppingListDetail.as_view('shopping-list-detail'))
app.add_url_rule('/remove-shopping-list', view_func=RemoveShoppingList.as_view('remove-shopping-list'))

# app conf
app.debug = True
app.secret_key = config['SECRET_KEY']['KEY']

if __name__ == '__main__':
    app.run()
<|endoftext|>


<commit_before>import StringIO
import json
import logging
import random
import urllib
import urllib2
import time
import math
import re
import requests
import requests_toolbelt.adapters.appengine

# Use the App Engine Requests adapter. This makes sure that Requests uses
# URLFetch.
requests_toolbelt.adapters.appengine.monkeypatch()

# sending images
try:
    from PIL import Image
except:
    pass
import multipart

# standard app engineimports
from google.appengine.api import urlfetch
from google.appengine.ext import deferred
from google.appengine.ext import ndb
from google.appengine.api.taskqueue import TaskRetryOptions
import webapp2

from exchanges import (
    KrakenExchange,
    BittrexExchange,
    ASSETPAIRS,
    ASSETS,
    BITT_ASSETPAIRS,
)

TOKEN = '363749995:AAEMaasMVLSPqSuSr1MiEFcgQH_Yn88hlbg'

BASE_URL = 'https://api.telegram.org/bot' + TOKEN + '/'

urlfetch.set_default_fetch_deadline(60)

ALERTS = set()

def deffered_track_pair_price(pair, current_price, target_price, chat_id, message_id):
    alert_key = (pair, target_price)
    logging.info("Checking price alert..{} if {}".format(pair, target_price))
    kraken = KrakenExchange()
    ticker = kraken.getTicker(pair=ASSETPAIRS[pair])
    askPrice = float(ticker['Ask Price'][0])
    bidPrice = float(ticker['Bid Price'][0])
    live_price = (askPrice + bidPrice) / 2
    target_price = float(target_price)
    if current_price < target_price and live_price >= target_price:
        ALERTS.remove(alert_key)
        reply_message(
            chat_id=chat_id,
            message_id=message_id,
            msg="{} just hit {}!".format(
                pair, live_price
            )
        )
    elif current_price > target_price and live_price <= target_price:
        ALERTS.remove(alert_key)
        reply_message(
            chat_id=chat_id,
            message_id=message_id,
            msg="{} just hit {}!".format(
                pair, live_price
            )
        )
    else:
        raise Exception("Alert not hit, fail task so it is retried")

def track_pair_price(pair, current_price, target_price, chat_id, message_id):
    ALERTS.add(
        (pair, target_price)
    )

    deferred.defer(
        deffered_track_pair_price,
        pair, current_price, target_price, chat_id, message_id,
        _retry_options=TaskRetryOptions(
            min_backoff_seconds=60,
            task_age_limit=86400
        ) # 1 day
    )

# ================================

class EnableStatus(ndb.Model):
    # key name: str(chat_id)
    enabled = ndb.BooleanProperty(indexed=False, default=False)

# ================================

def setEnabled(chat_id, yes):
    es = EnableStatus.get_or_insert(str(chat_id))
    es.enabled = yes
    es.put()

def getEnabled(chat_id):
    es = EnableStatus.get_by_id(str(chat_id))
    if es:
        return es.enabled
    return False

# ================================

class MeHandler(webapp2.RequestHandler):
    def get(self):
        urlfetch.set_default_fetch_deadline(60)
        self.response.write(json.dumps(json.load(urllib2.urlopen(BASE_URL + 'getMe'))))

class GetUpdatesHandler(webapp2.RequestHandler):
    def get(self):
        urlfetch.set_default_fetch_deadline(60)
        self.response.write(json.dumps(json.load(urllib2.urlopen(BASE_URL + 'getUpdates'))))

class SetWebhookHandler(webapp2.RequestHandler):
    def get(self):
        urlfetch.set_default_fetch_deadline(60)
        url = self.request.get('url')
        if url:
            self.response.write(json.dumps(json.load(urllib2.urlopen(BASE_URL + 'setWebhook', urllib.urlencode({'url': url})))))

def reply_message(chat_id, message_id, msg=None, img=None):
    resp = ''

    try:
        if msg:
            resp = urllib2.urlopen(BASE_URL + 'sendMessage', urllib.urlencode({
                'chat_id': str(chat_id),
                'text': msg.encode('utf-8'),
                'disable_web_page_preview': 'true',
                'reply_to_message_id': str(message_id),
                'parse_mode': 'Markdown'
            })).read()
        elif img:
            resp = multipart.post_multipart(BASE_URL + 'sendPhoto', [
                ('chat_id', str(chat_id)),
                ('reply_to_message_id', str(message_id)),
            ], [
                ('photo', 'image.jpg', img),
            ])
        else:
            logging.error('no msg or img specified')
            resp = None
    except Exception as exc:
        logging.error("ERROR %s" % exc)
        pass

    logging.info('send response:')
    logging.info(resp)

class WebhookHandler(webapp2.RequestHandler):
    def post(self):
        urlfetch.set_default_fetch_deadline(60)
        body = json.loads(self.request.body)
        logging.info('request body:')
        logging.info(body)
        self.response.write(json.dumps(body))

        update_id = body['update_id']
        try:
            message = body['message']
        except:
            message = body['edited_message']
        message_id = message.get('message_id')
        date = message.get('date')
        text = message.get('text')
        fr = message.get('from')
        chat = message['chat']
        chat_id = chat['id']

        def reply(msg=None, img=None):
            reply_message(msg=msg, img=img, chat_id=chat_id, message_id=message_id)

        if not text:
            logging.info('no text')
            return

        if text.startswith('/'):
            text_kraken = re.sub('(\/btc)', '/xbt', text)
            text_kraken = re.sub('(btc$)', 'xbt', text)
            text_kraken = re.sub('(btc\s+)', 'xbt ', text)
            if text == '/start':
                reply('Bot enabled')
                setEnabled(chat_id, True)
            if text == '/alerts':
                reply(
                    "*Alerts*\n{}".format(
                        "\n".join([
                            "{}: {}".format(pair, price)
                            for pair, price in ALERTS
                        ])
                    )
                )

            elif text == '/stop':
                reply('Bot disabled')
                setEnabled(chat_id, False)
            elif text == '/rules':
                reply('1. You do not talk about WHALE HUNTERS \n2. You DO NOT talk about WHALE HUNTERS \n3. Master level of TA skills required \n3.141592 Bring pie \n4. Inactive members will be banned')
            elif text == '/image':
                img = Image.new('RGB', (512, 512))
                base = random.randint(0, 16777216)
                pixels = [base+i*j for i in range(512) for j in range(512)]
                img.putdata(pixels)
                output = StringIO.StringIO()
                img.save(output, 'JPEG')
                reply(img=output.getvalue())
            elif text == '/help' or text == '/options':
                r = '/rules : show rules\n/image : generate an image\n/time(s) : get server time\n/assets : list of assets\n/pairs : list of all pairs (long)\n/<asset> : show this assets pairs\n/<assetpair> : show assetpairs price\n/alerts : show alerts'
                reply(r)
            elif text == '/time' or text == '/times':
                time = KrakenExchange().getServerTime()['rfc1123']
                r = 'Kraken server time: {}'.format(time)
                reply(r)
            elif text == '/assets':
                r = 'Reply with /<asset> to get its pairs\n{}'.format(', '.join(ASSETS))
                reply(r)
            elif text == '/pairs':
                assets = ASSETPAIRS.keys()
                assets.sort()
                r = 'Reply with /<assetpair> to get bid/ask prices\n{}'.format(', '.join(assets))
                reply(r)
            elif text == '/magic':
                r = 'https://media.giphy.com/media/12NUbkX6p4xOO4/giphy.gif'
                reply(r)
            elif text[1:].upper() in ASSETS:
                pairs = []
                for pair in ASSETPAIRS:
                    if pair[:3] == text[1:].upper()[:3]:
                        pairs.append(pair)
                r = 'Reply with /<assetpair> to get bid/ask prices\n{}'.format(', '.join(pairs))
                reply(r)

            elif text_kraken.split(' ')[0][1:].upper() in ASSETPAIRS.keys():
                pair = text_kraken.split(' ')[0][1:].upper()
                kraken = KrakenExchange()
                ticker = kraken.getTicker(pair=ASSETPAIRS[pair])
                askPrice = float(ticker['Ask Price'][0])
                bidPrice = float(ticker['Bid Price'][0])
                price = (askPrice + bidPrice) / 2
                highPrice = float(ticker['High'][0])
                lowPrice = float(ticker['Low'][0])
                # time = kraken.serverTime['rfc1123']
                r = ""
                if len(text_kraken.split(' ')) > 1:
                    if text_kraken.split(' ')[1] == 'fib':
                        l_one = highPrice
                        l_two = highPrice - ((highPrice - lowPrice) * 0.236)
                        l_three = highPrice - ((highPrice - lowPrice) * 0.382)
                        l_four = highPrice - ((highPrice - lowPrice) * 0.5)
                        l_five = highPrice - ((highPrice - lowPrice) * 0.618)
                        l_six = highPrice - ((highPrice - lowPrice) * 0.786)
                        l_seven = lowPrice
                        l_eight = highPrice - ((highPrice - lowPrice) * 1.272)
                        l_nine = highPrice - ((highPrice - lowPrice) * 1.618)

                        r = '*KRAKEN:{0}* 24h fib levels\n\n*0%*: {1}\n*23.6%*: {2}\n*38.2%*: {3}\n*50%*: {4}\n*61.8%*: {5}\n*78.6%*: {6}\n*100%*: {7}\n\n*127.2%*: {8}\n*161.8%*: {9}\n'.format(pair, l_one, l_two, l_three, l_four, l_five, l_six, l_seven, l_eight, l_nine)
                    if text_kraken.split(' ')[1] == 'book':
                        order_book = kraken.getOrderBook(pair=ASSETPAIRS[pair])
                        book = order_book[ASSETPAIRS[pair]]
                        r = "*OrderBook* KRAKEN:{0} \n*Asks*\n{1}\n\n*Bids*\n{2}".format(
                            pair,
                            "\n".join(
                                ["{} {}".format(ask[0], ask[1]) for ask in book['asks'][:10]]
                            ),
                            "\n".join(
                                ["{} {}".format(bid[0], bid[1]) for bid in book['bids'][:10]]
                            ),
                        )
                    if text_kraken.split(' ')[1] == 'alert':
                        try:
                            target_price = text_kraken.split(' ')[2]
                            track_pair_price(pair, price, target_price, chat_id, message_id)
                            r = 'You want me to keep an eye on your {}? I will let you know if it rises or drops to {}'.format(
                                pair, target_price
                            )
                            logging.info(r)
                        except IndexError:
                            r = 'Tell me what price you want an alert for, doofus!'
                else:
                    r = '*KRAKEN:{}* \n*Price:* {} \n*---* \n*High:* {} \n*Low:* {}'.format(pair, price, highPrice, lowPrice)
                # r += '\n\n_updated: {}_'.format(time)
                reply(r)

            elif text.split(' ')[0][1:].upper() in BITT_ASSETPAIRS:
                # TODO: insert bittrex methods here
                pair = text.split(' ')[0][1:]
                bittrex = BittrexExchange()
                ticker = bittrex.getTicker(pair=pair)

                askPrice = float(ticker['Ask Price'])
                bidPrice = float(ticker['Bid Price'])
                price = (askPrice + bidPrice) / 2
                highPrice = float(ticker['High'])
                lowPrice = float(ticker['Low'])
                r = ""

                if len(text.split(' ')) > 1:
                    if text.split(' ')[1] == 'fib':
                        l_one = highPrice
                        l_two = highPrice - ((highPrice - lowPrice) * 0.236)
                        l_three = highPrice - ((highPrice - lowPrice) * 0.382)
                        l_four = highPrice - ((highPrice - lowPrice) * 0.5)
                        l_five = highPrice - ((highPrice - lowPrice) * 0.618)
                        l_six = highPrice - ((highPrice - lowPrice) * 0.786)
                        l_seven = lowPrice
                        l_eight = highPrice - ((highPrice - lowPrice) * 1.272)
                        l_nine = highPrice - ((highPrice - lowPrice) * 1.618)

                        r = '*BITTREX:{0}* 24h fib levels\n\n*0%*: {1}\n*23.6%*: {2}\n*38.2%*: {3}\n*50%*: {4}\n*61.8%*: {5}\n*78.6%*: {6}\n*100%*: {7}\n\n*127.2%*: {8}\n*161.8%*: {9}\n'.format(pair, l_one, l_two, l_three, l_four, l_five, l_six, l_seven, l_eight, l_nine)

                else:
                    r = '*BITTREX:{}* \n*Price:* {} \n*---* \n*High:* {} \n*Low:* {}'.format(pair, price, highPrice, lowPrice)
                reply(r)

            elif len(text) == 4 or len(text) == 7:
                reply('This asset(pair) is not recognized. Pick one from the /assets list, stupid.')
            else:
                reply('You know, this sort of behaviour could qualify as sexual harassment.')

        # bot text reply's

        elif 'beach' in text:
            reply('dont forget to bring a towel')
        # elif ('sell' in text or 'dropping' in text or 'dumping' in text) and random.choice([True, False]):
        #     reply('weak hands!')
        # elif 'what time' in text:
        #     reply('look at the corner of your screen!')
        # elif 'moon' in text:
        #     reply('http://www.louwmanexclusive.com/nl/brands/lamborghini/')
        # elif 'bitch' in text:
        #     reply('dont talk to me like that!')
        # elif 'penny' in text:
        #     reply('Dont talk behind my back!')
        # elif 'kraken' in text.lower():
        #     fuck_kraken = ['Haha! Kraken...', 'Fuck Kraken!', 'Anything but kraken', 'Kra-what?', 'How about no?']
        #     reply(random.choice(fuck_kraken))
        elif 'ratio' in text.lower():
            reply("Haha, Pan Sai will make fun of you and not explain. You Better know what you mean.")
        else:
            if getEnabled(chat_id):
                reply('I got your message! (but I do not know how to answer)')
            else:
                logging.info('not enabled for chat_id {}'.format(chat_id))

app = webapp2.WSGIApplication([
    ('/me', MeHandler),
    ('/updates', GetUpdatesHandler),
    ('/set_webhook', SetWebhookHandler),
    ('/webhook', WebhookHandler),
], debug=True)
<commit_msg>no more bs<commit_after>import StringIO
import json
import logging
import random
import urllib
import urllib2
import time
import math
import re
import requests
import requests_toolbelt.adapters.appengine

# Use the App Engine Requests adapter. This makes sure that Requests uses
# URLFetch.
requests_toolbelt.adapters.appengine.monkeypatch()

# sending images
try:
    from PIL import Image
except:
    pass
import multipart

# standard app engineimports
from google.appengine.api import urlfetch
from google.appengine.ext import deferred
from google.appengine.ext import ndb
from google.appengine.api.taskqueue import TaskRetryOptions
import webapp2

from exchanges import (
    KrakenExchange,
    BittrexExchange,
    ASSETPAIRS,
    ASSETS,
    BITT_ASSETPAIRS,
)

TOKEN = '363749995:AAEMaasMVLSPqSuSr1MiEFcgQH_Yn88hlbg'

BASE_URL = 'https://api.telegram.org/bot' + TOKEN + '/'

urlfetch.set_default_fetch_deadline(60)

ALERTS = set()

def deffered_track_pair_price(pair, current_price, target_price, chat_id, message_id):
    alert_key = (pair, target_price)
    logging.info("Checking price alert..{} if {}".format(pair, target_price))
    kraken = KrakenExchange()
    ticker = kraken.getTicker(pair=ASSETPAIRS[pair])
    askPrice = float(ticker['Ask Price'][0])
    bidPrice = float(ticker['Bid Price'][0])
    live_price = (askPrice + bidPrice) / 2
    target_price = float(target_price)
    if current_price < target_price and live_price >= target_price:
        ALERTS.remove(alert_key)
        reply_message(
            chat_id=chat_id,
            message_id=message_id,
            msg="{} just hit {}!".format(
                pair, live_price
            )
        )
    elif current_price > target_price and live_price <= target_price:
        ALERTS.remove(alert_key)
        reply_message(
            chat_id=chat_id,
            message_id=message_id,
            msg="{} just hit {}!".format(
                pair, live_price
            )
        )
    else:
        raise Exception("Alert not hit, fail task so it is retried")

def track_pair_price(pair, current_price, target_price, chat_id, message_id):
    ALERTS.add(
        (pair, target_price)
    )

    deferred.defer(
        deffered_track_pair_price,
        pair, current_price, target_price, chat_id, message_id,
        _retry_options=TaskRetryOptions(
            min_backoff_seconds=60,
            task_age_limit=86400
        ) # 1 day
    )

# ================================

class EnableStatus(ndb.Model):
    # key name: str(chat_id)
    enabled = ndb.BooleanProperty(indexed=False, default=False)

# ================================

def setEnabled(chat_id, yes):
    es = EnableStatus.get_or_insert(str(chat_id))
    es.enabled = yes
    es.put()

def getEnabled(chat_id):
    es = EnableStatus.get_by_id(str(chat_id))
    if es:
        return es.enabled
    return False

# ================================

class MeHandler(webapp2.RequestHandler):
    def get(self):
        urlfetch.set_default_fetch_deadline(60)
        self.response.write(json.dumps(json.load(urllib2.urlopen(BASE_URL + 'getMe'))))

class GetUpdatesHandler(webapp2.RequestHandler):
    def get(self):
        urlfetch.set_default_fetch_deadline(60)
        self.response.write(json.dumps(json.load(urllib2.urlopen(BASE_URL + 'getUpdates'))))

class SetWebhookHandler(webapp2.RequestHandler):
    def get(self):
        urlfetch.set_default_fetch_deadline(60)
        url = self.request.get('url')
        if url:
            self.response.write(json.dumps(json.load(urllib2.urlopen(BASE_URL + 'setWebhook', urllib.urlencode({'url': url})))))

def reply_message(chat_id, message_id, msg=None, img=None):
    resp = ''

    try:
        if msg:
            resp = urllib2.urlopen(BASE_URL + 'sendMessage', urllib.urlencode({
                'chat_id': str(chat_id),
                'text': msg.encode('utf-8'),
                'disable_web_page_preview': 'true',
                'reply_to_message_id': str(message_id),
                'parse_mode': 'Markdown'
            })).read()
        elif img:
            resp = multipart.post_multipart(BASE_URL + 'sendPhoto', [
                ('chat_id', str(chat_id)),
                ('reply_to_message_id', str(message_id)),
            ], [
                ('photo', 'image.jpg', img),
            ])
        else:
            logging.error('no msg or img specified')
            resp = None
    except Exception as exc:
        logging.error("ERROR %s" % exc)
        pass

    logging.info('send response:')
    logging.info(resp)

class WebhookHandler(webapp2.RequestHandler):
    def post(self):
        urlfetch.set_default_fetch_deadline(60)
        body = json.loads(self.request.body)
        logging.info('request body:')
        logging.info(body)
        self.response.write(json.dumps(body))

        update_id = body['update_id']
        try:
            message = body['message']
        except:
            message = body['edited_message']
        message_id = message.get('message_id')
        date = message.get('date')
        text = message.get('text')
        fr = message.get('from')
        chat = message['chat']
        chat_id = chat['id']

        def reply(msg=None, img=None):
            reply_message(msg=msg, img=img, chat_id=chat_id, message_id=message_id)

        if not text:
            logging.info('no text')
            return

        if text.startswith('/'):
            text_kraken = re.sub('(\/btc)', '/xbt', text)
            text_kraken = re.sub('(btc$)', 'xbt', text)
            text_kraken = re.sub('(btc\s+)', 'xbt ', text)
            if text == '/start':
                reply('Bot enabled')
                setEnabled(chat_id, True)
            if text == '/alerts':
                reply(
                    "*Alerts*\n{}".format(
                        "\n".join([
                            "{}: {}".format(pair, price)
                            for pair, price in ALERTS
                        ])
                    )
                )

            elif text == '/stop':
                reply('Bot disabled')
                setEnabled(chat_id, False)
            elif text == '/rules':
                reply('1. You do not talk about WHALE HUNTERS \n2. You DO NOT talk about WHALE HUNTERS \n3. Master level of TA skills required \n3.141592 Bring pie \n4. Inactive members will be banned')
            elif text == '/image':
                img = Image.new('RGB', (512, 512))
                base = random.randint(0, 16777216)
                pixels = [base+i*j for i in range(512) for j in range(512)]
                img.putdata(pixels)
                output = StringIO.StringIO()
                img.save(output, 'JPEG')
                reply(img=output.getvalue())
            elif text == '/help' or text == '/options':
                r = '/rules : show rules\n/image : generate an image\n/time(s) : get server time\n/assets : list of assets\n/pairs : list of all pairs (long)\n/<asset> : show this assets pairs\n/<assetpair> : show assetpairs price\n/alerts : show alerts'
                reply(r)
            elif text == '/time' or text == '/times':
                time = KrakenExchange().getServerTime()['rfc1123']
                r = 'Kraken server time: {}'.format(time)
                reply(r)
            elif text == '/assets':
                r = 'Reply with /<asset> to get its pairs\n{}'.format(', '.join(ASSETS))
                reply(r)
            elif text == '/pairs':
                assets = ASSETPAIRS.keys()
                assets.sort()
                r = 'Reply with /<assetpair> to get bid/ask prices\n{}'.format(', '.join(assets))
                reply(r)
            elif text == '/magic':
                r = 'https://media.giphy.com/media/12NUbkX6p4xOO4/giphy.gif'
                reply(r)
            elif text[1:].upper() in ASSETS:
                pairs = []
                for pair in ASSETPAIRS:
                    if pair[:3] == text[1:].upper()[:3]:
                        pairs.append(pair)
                r = 'Reply with /<assetpair> to get bid/ask prices\n{}'.format(', '.join(pairs))
                reply(r)

            elif text_kraken.split(' ')[0][1:].upper() in ASSETPAIRS.keys():
                pair = text_kraken.split(' ')[0][1:].upper()
                kraken = KrakenExchange()
                ticker = kraken.getTicker(pair=ASSETPAIRS[pair])
                askPrice = float(ticker['Ask Price'][0])
                bidPrice = float(ticker['Bid Price'][0])
                price = (askPrice + bidPrice) / 2
                highPrice = float(ticker['High'][0])
                lowPrice = float(ticker['Low'][0])
                # time = kraken.serverTime['rfc1123']
                r = ""
                if len(text_kraken.split(' ')) > 1:
                    if text_kraken.split(' ')[1] == 'fib':
                        l_one = highPrice
                        l_two = highPrice - ((highPrice - lowPrice) * 0.236)
                        l_three = highPrice - ((highPrice - lowPrice) * 0.382)
                        l_four = highPrice - ((highPrice - lowPrice) * 0.5)
                        l_five = highPrice - ((highPrice - lowPrice) * 0.618)
                        l_six = highPrice - ((highPrice - lowPrice) * 0.786)
                        l_seven = lowPrice
                        l_eight = highPrice - ((highPrice - lowPrice) * 1.272)
                        l_nine = highPrice - ((highPrice - lowPrice) * 1.618)

                        r = '*KRAKEN:{0}* 24h fib levels\n\n*0%*: {1}\n*23.6%*: {2}\n*38.2%*: {3}\n*50%*: {4}\n*61.8%*: {5}\n*78.6%*: {6}\n*100%*: {7}\n\n*127.2%*: {8}\n*161.8%*: {9}\n'.format(pair, l_one, l_two, l_three, l_four, l_five, l_six, l_seven, l_eight, l_nine)
                    if text_kraken.split(' ')[1] == 'book':
                        order_book = kraken.getOrderBook(pair=ASSETPAIRS[pair])
                        book = order_book[ASSETPAIRS[pair]]
                        r = "*OrderBook* KRAKEN:{0} \n*Asks*\n{1}\n\n*Bids*\n{2}".format(
                            pair,
                            "\n".join(
                                ["{} {}".format(ask[0], ask[1]) for ask in book['asks'][:10]]
                            ),
                            "\n".join(
                                ["{} {}".format(bid[0], bid[1]) for bid in book['bids'][:10]]
                            ),
                        )
                    if text_kraken.split(' ')[1] == 'alert':
                        try:
                            target_price = text_kraken.split(' ')[2]
                            track_pair_price(pair, price, target_price, chat_id, message_id)
                            r = 'You want me to keep an eye on your {}? I will let you know if it rises or drops to {}'.format(
                                pair, target_price
                            )
                            logging.info(r)
                        except IndexError:
                            r = 'Tell me what price you want an alert for, doofus!'
                else:
                    r = '*KRAKEN:{}* \n*Price:* {} \n*---* \n*High:* {} \n*Low:* {}'.format(pair, price, highPrice, lowPrice)
                # r += '\n\n_updated: {}_'.format(time)
                reply(r)

            elif text.split(' ')[0][1:].upper() in BITT_ASSETPAIRS:
                # TODO: insert bittrex methods here
                pair = text.split(' ')[0][1:]
                bittrex = BittrexExchange()
                ticker = bittrex.getTicker(pair=pair)

                askPrice = float(ticker['Ask Price'])
                bidPrice = float(ticker['Bid Price'])
                price = (askPrice + bidPrice) / 2
                highPrice = float(ticker['High'])
                lowPrice = float(ticker['Low'])
                r = ""

                if len(text.split(' ')) > 1:
                    if text.split(' ')[1] == 'fib':
                        l_one = highPrice
                        l_two = highPrice - ((highPrice - lowPrice) * 0.236)
                        l_three = highPrice - ((highPrice - lowPrice) * 0.382)
                        l_four = highPrice - ((highPrice - lowPrice) * 0.5)
                        l_five = highPrice - ((highPrice - lowPrice) * 0.618)
                        l_six = highPrice - ((highPrice - lowPrice) * 0.786)
                        l_seven = lowPrice
                        l_eight = highPrice - ((highPrice - lowPrice) * 1.272)
                        l_nine = highPrice - ((highPrice - lowPrice) * 1.618)

                        r = '*BITTREX:{0}* 24h fib levels\n\n*0%*: {1}\n*23.6%*: {2}\n*38.2%*: {3}\n*50%*: {4}\n*61.8%*: {5}\n*78.6%*: {6}\n*100%*: {7}\n\n*127.2%*: {8}\n*161.8%*: {9}\n'.format(pair, l_one, l_two, l_three, l_four, l_five, l_six, l_seven, l_eight, l_nine)

                else:
                    r = '*BITTREX:{}* \n*Price:* {} \n*---* \n*High:* {} \n*Low:* {}'.format(pair, price, highPrice, lowPrice)
                reply(r)

            elif len(text) == 4 or len(text) == 7:
                reply('This asset(pair) is not recognized. Pick one from the /assets list, stupid.')
            else:
                reply('You know, this sort of behaviour could qualify as sexual harassment.')

        # bot text reply's

        elif 'beach' in text:
            reply('dont forget to bring a towel')
        # elif ('sell' in text or 'dropping' in text or 'dumping' in text) and random.choice([True, False]):
        #     reply('weak hands!')
        # elif 'what time' in text:
        #     reply('look at the corner of your screen!')
        # elif 'moon' in text:
        #     reply('http://www.louwmanexclusive.com/nl/brands/lamborghini/')
        # elif 'bitch' in text:
        #     reply('dont talk to me like that!')
        # elif 'penny' in text:
        #     reply('Dont talk behind my back!')
        # elif 'kraken' in text.lower():
        #     fuck_kraken = ['Haha! Kraken...', 'Fuck Kraken!', 'Anything but kraken', 'Kra-what?', 'How about no?']
        #     reply(random.choice(fuck_kraken))
        # elif 'ratio' in text.lower():
        #     reply("Haha, Pan Sai will make fun of you and not explain. You Better know what you mean.")
        else:
            if getEnabled(chat_id):
                reply('I got your message! (but I do not know how to answer)')
            else:
                logging.info('not enabled for chat_id {}'.format(chat_id))

app = webapp2.WSGIApplication([
    ('/me', MeHandler),
    ('/updates', GetUpdatesHandler),
    ('/set_webhook', SetWebhookHandler),
    ('/webhook', WebhookHandler),
], debug=True)
<|endoftext|>


<commit_before>import os.path
from os import listdir
from os.path import join

# RRD module
import rrdtool

db_path = '/var/lib/astor2-rrdd/rrd/'
png_path = '/var/lib/astor2-rrdd/png/'

# Update existing rrd database
# Main function
def commit():
    # RRD databases list
    rrd = { 'mem': 'Memory.rrd', 'net': 'Network.rrd', 'cpu': 'Cpu.rrd' }
    for key, value in rrd.iteritems():
        db_check = check_db(rrd, key)
        if db_check == True:
            update_db(rrd, key)
        else:
            print('DB '+value+' created')
            new_db(rrd, key)

# Check of rrd db file
def check_db(rrd, db_type):
    if db_type == 'net':
        ifaces = interfaces()
        for i in ifaces:
            rrd_db = db_path + i + '.' + rrd[db_type]
            if os.path.isfile(rrd_db) != True:
                new_db(rrd, db_type)
            else:
                return True
    else:
        rrd_db = db_path + rrd[db_type]
        return os.path.isfile(rrd_db)

# System
########

# Get network interfaces list
def interfaces():
    sys_path = '/sys/class/net'
    ifaces = [ f for f in listdir(sys_path) if join(sys_path, f) ]
    ifaces.remove('lo')
    return ifaces

# Get traffic values
def get_traf():
    ifaces = interfaces()
    traffic = {}

    # Parsing /proc/net/dev
    proc = '/proc/net/dev'
    f = open(proc, "r")
    for line in f.readlines():
        bytes = line.split()
        for i in ifaces:
            net = bytes[0]
            net = net[:-1]
            if i == net:
                traffic[i] = { 'in': bytes[1], 'out': bytes[9] }
    return traffic

# Get memory function
def get_mem():
    proc = '/proc/meminfo'
    mem = {}
    f = open(proc, "r")
    for line in f.readlines():
        memory = line.split()
        m = memory[0][:-1]
        if m == 'MemTotal':
            mem['total'] = memory[1]
        elif m == 'MemFree':
            mem['free'] = memory[1]
        elif m == 'Buffers':
            mem['buffers'] = memory[1]
        elif m == 'Cached':
            mem['cached'] = memory[1]
        elif m == 'SwapCached':
            mem['swap'] = memory[1]

    mem['used'] = (int( mem['total'] ) - int( mem['free'] )) - ( int(mem['cached']) - int(mem['buffers']) )
    return mem

# Get phisicals CPU
def cpu_id():
    proc = '/proc/cpuinfo'
    f = open(proc, "r")

    # Physical id counter
    phys = 1
    for line in f.readlines():
        l = line.split(':')
        name = l[0][:-1]
        if name == 'physical id':
            value = l[1]
            print name, value
            if int(value) >= phys:
                phys = phys + 1

    return phys

# Get system output.
# !!! Will be removed later !!!
def get_cmd(cmd):
    import os
    return int(os.popen(cmd).read())

# End of system
###############

# Update DB functions
#####################

# Update rrd database
def update_db(rrd, db_type):
    rrd_db = db_path + rrd[db_type]
    # Update network DB
    if db_type == 'net':
        update_net(rrd)
    elif db_type == 'mem':
        update_mem(rrd, db_type)

# Update memory DB
def update_mem(rrd, db_type):
        rrd_db = db_path + rrd[db_type]
        #Get memmory data
        mem = get_mem()

        print mem # Debug
        # Update rrd db
        print('Updating mem DB')
        rrdtool.update( rrd_db, 'N:%s:%s:%s:%s:%s' % (int(mem['free']),
            int(mem['total']), int(mem['buffers']), int(mem['cached']), mem['used']) )

        # Generate graph
        graph(rrd, db_type)
        print('Memory graph generated')

def update_net(rrd):
    traffic = get_traf()
    for i in traffic.iteritems():
        rrd_db = db_path + i[0] + '.' + rrd['net']
        # Update rrd db
        rrdtool.update(rrd_db, 'N:%s:%s' % (i[1]['in'], i[1]['out']))
        # Generate graph
        graph(rrd, 'net')

# End of update DB functions
############################

# Create graph functions
########################

# Switches for graphics
def graph(rrd, db_type):
    if db_type == 'net':
        graph_net(rrd)
        print('Net graphs generated')
    elif db_type == 'mem':
        graph_mem(rrd, db_type)

# Generate graphic for memory usage
def graph_mem(rrd, db_type):
    png = png_path + rrd[db_type] + '.png'
    db = db_path + rrd[db_type]
    rrdtool.graph(png, '--start', 'end-120000s', '--width', '400',
            "--vertical-label=Gb", "-M",
            '--watermark=OpenSAN2', '-w 800',
            '--lower-limit', '0', '-E', '-i', '-r',
            "DEF:free="+ db +":free:LAST",
            "DEF:total="+ db +":total:LAST",
            # "DEF:buffers="+ db +":buffers:AVERAGE",
            # "DEF:cached="+ db +":cached:AVERAGE",
            # "DEF:used="+ db +":used:AVERAGE",
            "AREA:free#0000FF:free\\n",
            # "LINE2:cached#00FF00:cached\\r",
            # "AREA:used#FF0000:used\\r",
            "AREA:total#F00CC0:total\\n" )
            # "LINE:buffers#222222:buffers\\r")

# Generate graphic for network interfaces
def graph_net(rrd):
    ifaces = interfaces()
    for i in ifaces:
        png = png_path + i + '.' + rrd['net'] + '.png'
        db = db_path + i + '.' + rrd['net']
        rrdtool.graph(png, '--start', 'end-2h',
            '--title', 'Network interface ' + i,
            '--width', '400', "--vertical-label=Num",
            '--slope-mode', '-m', '1', '--dynamic-labels',
            '--watermark=OpenSAN2', '-w 600',
            '--lower-limit', '0', '-E', '-i', '-r',
            "DEF:in="+ db +":in:AVERAGE",
            "DEF:out="+ db +":out:AVERAGE",
            "LINE1:in#0000FF:in",
            "LINE2:out#00FF00:out\\n",
            )

# End of create graph functions
###############################

# rrdtool create functions
# Needs to rewrite
##########################

# Create new db
def new_db(rrd, db_type):
    rrd_db = db_path + rrd[db_type]
    if db_type == 'net':
        create_net(rrd)
    elif db_type == 'mem':
        create_mem(rrd_db)
    elif db_type == 'cpu':
        create_cpu(rrd_db)

# Create new network DB
def create_net(rrd):
    ifaces = interfaces()
    for i in ifaces:
        rrd_db = db_path + i + '.' + rrd['net']
        data_sources=[ 'DS:in:DERIVE:600:0:12500000',
                    'DS:out:DERIVE:600:0:12500000'
                    ]
        # Create network database
        rrdtool.create( rrd_db,
                     '--start', '920804400',
                     data_sources,
                     'RRA:AVERAGE:0.5:1:576',
                     'RRA:AVERAGE:0.5:6:672',
                     'RRA:AVERAGE:0.5:24:732',
                     'RRA:AVERAGE:0.5:144:1460'
                    )

# Create new memory DB
def create_mem(rrd_db):
    data_sources = [ 'DS:free:DERIVE:200:0:12500000',
                'DS:total:DERIVE:200:0:12500000',
                'DS:cached:DERIVE:200:0:12500000',
                'DS:buffers:DERIVE:200:0:12500000',
                'DS:used:DERIVE:200:0:12500000'
                ]
    # Create network database
    rrdtool.create( rrd_db,
                 data_sources,
                 'RRA:LAST:0.5:1:1',
                 'RRA:LAST:0.5:6:10',
                 'RRA:LAST:0.5:1:24',
                 'RRA:LAST:0.5:1:24',
                 'RRA:LAST:0.5:1:24' )

# Create new CPU DB
def create_cpu(rrd_db):
    data_sources=[ 'DS:speed1:COUNTER:600:U:U',
                'DS:speed2:COUNTER:600:U:U',
                'DS:speed3:COUNTER:600:U:U' ]
    # Create network database
    rrdtool.create( rrd_db,
                 '--start', '920804400',
                 data_sources,
                 'RRA:AVERAGE:0.5:1:24',
                 'RRA:AVERAGE:0.5:6:10' )

# End of rrdtool create functions
#################################
<commit_msg>Memory graph creation update<commit_after>import os.path
from os import listdir
from os.path import join

# RRD module
import rrdtool

db_path = '/var/lib/astor2-rrdd/rrd/'
png_path = '/var/lib/astor2-rrdd/png/'

# Update existing rrd database
# Main function
def commit():
    # RRD databases list
    rrd = { 'mem': 'Memory.rrd', 'net': 'Network.rrd', 'cpu': 'Cpu.rrd' }
    for key, value in rrd.iteritems():
        db_check = check_db(rrd, key)
        if db_check == True:
            update_db(rrd, key)
        else:
            print('DB '+value+' created')
            new_db(rrd, key)

# Check of rrd db file
def check_db(rrd, db_type):
    if db_type == 'net':
        ifaces = interfaces()
        for i in ifaces:
            rrd_db = db_path + i + '.' + rrd[db_type]
            if os.path.isfile(rrd_db) != True:
                new_db(rrd, db_type)
            else:
                return True
    else:
        rrd_db = db_path + rrd[db_type]
        return os.path.isfile(rrd_db)

# System
########

# Get network interfaces list
def interfaces():
    sys_path = '/sys/class/net'
    ifaces = [ f for f in listdir(sys_path) if join(sys_path, f) ]
    ifaces.remove('lo')
    return ifaces

# Get traffic values
def get_traf():
    ifaces = interfaces()
    traffic = {}

    # Parsing /proc/net/dev
    proc = '/proc/net/dev'
    f = open(proc, "r")
    for line in f.readlines():
        bytes = line.split()
        for i in ifaces:
            net = bytes[0]
            net = net[:-1]
            if i == net:
                traffic[i] = { 'in': bytes[1], 'out': bytes[9] }
    return traffic

# Get memory function
def get_mem():
    proc = '/proc/meminfo'
    mem = {}
    f = open(proc, "r")
    for line in f.readlines():
        memory = line.split()
        m = memory[0][:-1]
        if m == 'MemTotal':
            mem['total'] = memory[1]
        elif m == 'MemFree':
            mem['free'] = memory[1]
        elif m == 'Buffers':
            mem['buffers'] = memory[1]
        elif m == 'Cached':
            mem['cached'] = memory[1]
        elif m == 'SwapCached':
            mem['swap'] = memory[1]

    mem['used'] = (int( mem['total'] ) - int( mem['free'] )) - ( int(mem['cached']) - int(mem['buffers']) )
    return mem

# Get phisicals CPU
def cpu_id():
    proc = '/proc/cpuinfo'
    f = open(proc, "r")

    # Physical id counter
    phys = 1
    for line in f.readlines():
        l = line.split(':')
        name = l[0][:-1]
        if name == 'physical id':
            value = l[1]
            print name, value
            if int(value) >= phys:
                phys = phys + 1

    return phys

# Get system output.
# !!! Will be removed later !!!
def get_cmd(cmd):
    import os
    return int(os.popen(cmd).read())

# End of system
###############

# Update DB functions
#####################

# Update rrd database
def update_db(rrd, db_type):
    rrd_db = db_path + rrd[db_type]
    # Update network DB
    if db_type == 'net':
        update_net(rrd)
    elif db_type == 'mem':
        update_mem(rrd, db_type)

# Update memory DB
def update_mem(rrd, db_type):
        rrd_db = db_path + rrd[db_type]
        #Get memmory data
        mem = get_mem()

        print mem # Debug
        # Update rrd db
        print('Updating mem DB')
        rrdtool.update( rrd_db, 'N:%s:%s:%s:%s:%s' % (int(mem['free']),
            int(mem['total']), int(mem['buffers']), int(mem['cached']), mem['used']) )

        # Generate graph
        graph(rrd, db_type)
        print('Memory graph generated')

def update_net(rrd):
    traffic = get_traf()
    for i in traffic.iteritems():
        rrd_db = db_path + i[0] + '.' + rrd['net']
        # Update rrd db
        rrdtool.update(rrd_db, 'N:%s:%s' % (i[1]['in'], i[1]['out']))
        # Generate graph
        graph(rrd, 'net')

# End of update DB functions
############################

# Create graph functions
########################

# Switches for graphics
def graph(rrd, db_type):
    if db_type == 'net':
        graph_net(rrd)
        print('Net graphs generated')
    elif db_type == 'mem':
        graph_mem(rrd, db_type)

# Generate graphic for memory usage
def graph_mem(rrd, db_type):
    png = png_path + rrd[db_type] + '.png'
    db = db_path + rrd[db_type]
    rrdtool.graph(png, '--start', '-1800', '--width', '400',
            "--vertical-label=Gb",
            '--watermark=OpenSAN2', '-w 800', '-r',
            # '--lower-limit', '0', '-E', '-i', '-r',
            "DEF:free="+ db +":free:AVERAGE",
            "DEF:total="+ db +":total:AVERAGE",
            'CDEF:total_x=total,1024,*',
            'CDEF:free_x=total,1024,*',
            "LINE1:free_x#0000FF:free\\n",
            "LINE2:total_x#F00CC0:total\\n" )

# Generate graphic for network interfaces
def graph_net(rrd):
    ifaces = interfaces()
    for i in ifaces:
        png = png_path + i + '.' + rrd['net'] + '.png'
        db = db_path + i + '.' + rrd['net']
        rrdtool.graph(png, '--start', 'end-6h',
            '--title', 'Network interface ' + i,
            '--width', '400', "--vertical-label=bits/s",
            '--slope-mode', '-m', '1', '--dynamic-labels',
            '--watermark=OpenSAN2', '-w 600',
            '--lower-limit', '0', '-E', '-i', '-r',
            "DEF:in="+ db +":in:AVERAGE",
            "DEF:out="+ db +":out:AVERAGE",
            "LINE1:in#0000FF:in",
            "LINE2:out#00FF00:out\\n",
            )

# End of create graph functions
###############################

# rrdtool create functions
# Needs to rewrite
##########################

# Create new db
def new_db(rrd, db_type):
    rrd_db = db_path + rrd[db_type]
    if db_type == 'net':
        create_net(rrd)
    elif db_type == 'mem':
        create_mem(rrd_db)
    elif db_type == 'cpu':
        create_cpu(rrd_db)

# Create new network DB
def create_net(rrd):
    ifaces = interfaces()
    for i in ifaces:
        rrd_db = db_path + i + '.' + rrd['net']
        data_sources=[ 'DS:in:COUNTER:120:0:U',
                    'DS:out:COUNTER:120:0:U'
                    ]
        # Create network database
        rrdtool.create( rrd_db,
                     '--start', '920804400',
                     data_sources,
                     'RRA:AVERAGE:0.5:1:360',
                     'RRA:AVERAGE:0.5:10:1008',
                     'RRA:AVERAGE:0.5:10:1008',
                    )

# Create new memory DB
def create_mem(rrd_db):
    data_sources = [ 'DS:free:GAUGE:120:0:U',
                'DS:total:GAUGE:120:0:U',
                'DS:cached:GAUGE:120:0:U',
                'DS:buffers:GAUGE:120:0:U',
                'DS:used:GAUGE:120:0:U'
                ]
    # Create network database
    rrdtool.create( rrd_db,
                 data_sources,
                 'RRA:AVERAGE:0.5:1:360',
                 'RRA:AVERAGE:0.5:10:1008,',
                 'RRA:MAX:0.5:10:1008'
                  )

# Create new CPU DB
def create_cpu(rrd_db):
    data_sources=[ 'DS:speed1:COUNTER:600:U:U',
                'DS:speed2:COUNTER:600:U:U',
                'DS:speed3:COUNTER:600:U:U' ]
    # Create network database
    rrdtool.create( rrd_db,
                 '--start', '920804400',
                 data_sources,
                 'RRA:AVERAGE:0.5:1:24',
                 'RRA:AVERAGE:0.5:6:10' )

# End of rrdtool create functions
#################################
<|endoftext|>


<commit_before># -*- coding: utf-8 -*-

#to use timer uncomment arrow import and timer marks

from twython import Twython
import urllib2
#import arrow

#momento = arrow.now('local') #just a way to test speed

#app settings, fill with your app credentials
app_key = ''
app_secret = ''
access_token = ''
access_token_secret = ''

twitter = Twython(app_key, app_secret, access_token, access_token_secret)
#tweets = twitter.search(q='#nowplaying spotify')

#define the tweets search
search = twitter.search

#function to get urls from a redirect
def get_redirected_url(url):
    opener = urllib2.build_opener(urllib2.HTTPRedirectHandler)
    request = opener.open(url)
    return request.url

#get the track from "open" urls
def track_number(url):
    return url.split("/")[4]

#get the tacks from tweets
def get_urls(magic_url):
	#different kinds of possible urls
    if "spoti.fi" in magic_url:
        true_url =  get_redirected_url(magic_url)
        tracked = track_number(true_url)

        if len(tracked) == 22:
            track = tracked

    elif "open.spotify.com" in magic_url:
        tracked = track_number(magic_url)
        if len(tracked) == 22:
            track = tracked
    else:
        error =  "Not a valid url"

    #print track
    return track

id_number = 0 #id for searchs in twitter
contador = 0 #used in the while to count tracks

#Is possible to get many bad urls or tweets where this code is not able to catch urls
#so this while does that at least you get 30 songs but for example you get 29 the while
#will get the next 15 tweets and extract the urls so you watchng to 44
while contador == 0 or contador <= 30:
    if id_number != 0:
        tweets = search(q='#nowplaying spotify', max_id= id_number) #make the search looking for older tweets
    else:
        tweets = search(q='#nowplaying spotify')#initial search

    for tweet in tweets['statuses']:
        magic_url = tweet['entities']['urls'][0]['expanded_url'].encode('utf-8')#the tweet url
        try:
            print "http://open.spotify.com/track/" + get_urls(magic_url)#get the spotify url
            contador += 1

        except:
            error = "Probably more than 1 url"

    id_number = tweets['statuses'][-1]['id'] # return the las id

#new_momento = arrow.now('local')#check again the time

#time = new_momento - momento
print "Printed " + str(contador) + " tracks in " #+ str(time)
<commit_msg>Update main.py<commit_after># -*- coding: utf-8 -*-

#to use timer uncomment arrow import and timer marks

from twython import Twython
import urllib2
#import arrow

#momento = arrow.now('local') #just a way to test speed

#app settings, fill with your app credentials
app_key = ''
app_secret = ''
access_token = ''
access_token_secret = ''

twitter = Twython(app_key, app_secret, access_token, access_token_secret)
#tweets = twitter.search(q='#nowplaying spotify')

#define the tweets search
search = twitter.search

#function to get urls from a redirect
def get_redirected_url(url):
    opener = urllib2.build_opener(urllib2.HTTPRedirectHandler)
    request = opener.open(url)
    return request.url

#get the track from "open" urls
def track_number(url):
    return url.split("/")[4]

#get the tacks from tweets
def get_urls(magic_url):
	#different kinds of possible urls
    if "spoti.fi" in magic_url:
        true_url =  get_redirected_url(magic_url)
        tracked = track_number(true_url)

        if len(tracked) == 22:
            track = tracked

    elif "open.spotify.com" in magic_url:
        tracked = track_number(magic_url)
        if len(tracked) == 22:
            track = tracked
    else:
        error =  "Not a valid url"

    #print track
    return track

id_number = 0 #id for searchs in twitter
contador = 0 #used in the while to count tracks
lista_usuarios = []

#Is possible to get many bad urls or tweets where this code is not able to catch urls
#so this while does that at least you get 30 songs but for example you get 29 the while
#will get the next 15 tweets and extract the urls so you watchng to 44
while contador == 0 or contador <= 30:
    if id_number != 0:
        tweets = search(q='#nowplaying spotify', max_id= id_number) #make the search looking for older tweets
    else:
        tweets = search(q='#nowplaying spotify')#initial search

    for tweet in tweets['statuses']:
        magic_url = tweet['entities']['urls'][0]['expanded_url'].encode('utf-8')#the tweet url
        try:
            if str(tweet['user']['screen_name']) not in lista_usuarios:
                lista_usuarios.append(str(tweet['user']['screen_name']))
            	print "http://open.spotify.com/track/" + get_urls(magic_url)#get the spotify url
            	contador += 1

        except:
            error = "Probably more than 1 url"

    id_number = tweets['statuses'][-1]['id'] # return the las id

#new_momento = arrow.now('local')#check again the time

#time = new_momento - momento
print "Printed " + str(contador) + " tracks in " #+ str(time)
<|endoftext|>


<commit_before>from __future__ import unicode_literals
import feedparser
import hashlib
from urllib.request import urlopen
from sopel.tools import SopelMemory
from sopel.module import commands, interval, NOLIMIT, require_privmsg, require_admin
from sopel.config.types import StaticSection, ListAttribute, ValidatedAttribute

MAX_HASHES = 400

class RSSSection(StaticSection):
    del_by_id = ListAttribute('del_by_id', default=False)
    feeds = ListAttribute('feeds', default=[])
    hashes = ListAttribute('hashes', default=[])
    monitoring_channel = ValidatedAttribute('monitoring_channel', default='')

def setup(bot):
    bot.config.define_section('rss', RSSSection)
    bot.memory['rss'] = SopelMemory()
    bot.memory['rss']['del_by_id'] = False
    bot.memory['rss']['feeds'] = []
    bot.memory['rss']['hashes'] = RingBuffer(MAX_HASHES)
    bot.memory['rss']['monitoring_channel'] = ''

    # check if a tables named hashes exists
    sql_check_table = "SELECT name FROM sqlite_master WHERE type='table' AND name='hashes'"
    result = bot.db.execute(sql_check_table).fetchall()

    # create table hashes in sqlite3 database provided by the sopel framework
    # use UNIQUE for column hash to minimize database writes by using
    # INSERT OR IGNORE (which is an abbreviation for INSERT ON CONFLICT IGNORE)
    if not result:
        sql_create_table = 'CREATE TABLE hashes (id INTEGER PRIMARY KEY, hash VARCHAR(32) UNIQUE)'
        bot.db.execute(sql_create_table)

    # read config from disk to memory
    __config_read(bot)

def configure(config):
    config.define_section('rss', RSSSection)
    config.rss.configure_setting('del_by_id', 'allow to delete feeds by index. this is potentially dangerous as the index of the remaining feeds may change after one feed has been deleted')
    config.rss.configure_setting('feeds', 'comma separated strings consisting of channel, name, url separated by spaces')
    config.rss.configure_setting('hashes', 'comma separated strings consisting of hashes of rss feed entries')
    config.rss.configure_setting('monitoring_channel', 'channel in which the bot will report errors')

def shutdown(bot):
    print('Shutting down!')
    bot.debug('rss', 'Shutting down!', 'always')

    # write config from memory to disk
    __config_save(bot)

@require_admin
@commands('rssadd')
def rssadd(bot, trigger):
    # check number of parameters
    for i in range(2,6):
        if trigger.group(i) is None:
            bot.say('syntax: {}{} <channel> <name> <url>'.format(bot.config.core.prefix, trigger.group(1)))
            return NOLIMIT

    # get arguments
    channel = trigger.group(3)
    name = trigger.group(4)
    url = trigger.group(5)

    # check that feed name is not a number
    try:
        int(name)
    except ValueError:
        pass
    else:
        bot.say('feed name "{}" is invalid, it has to contain at least one letter'.format(name))
        return NOLIMIT

    # check that feed name is unique
    for feed in bot.memory['rss']['feeds']:
        if name == feed['name']:
            bot.say('feed name "{}" is already in use, please choose a different one'.format(name))
            return NOLIMIT

    # check that channel starts with #
    if not channel.startswith('#'):
        bot.say('channel "{}" must begin with a "#"'.format(channel))
        return NOLIMIT

    # check that feed url is online
    try:
        with urlopen(url) as f:
            if f.status == 200:
                # save config to memory
                bot.memory['rss']['feeds'].append({'channel':channel, 'name':name, 'url':url})
                bot.say('rss feed "{}" added successfully'.format(url))
                bot.join(channel)
    except:
        bot.say('unable to add feed "{}": invalid url! syntax: .{} <channel> <name> <url>'.format(url, trigger.group(1)))
        return NOLIMIT

    __config_save(bot)

    return NOLIMIT

@require_admin
@commands('rssdel')
def rssdel(bot, trigger):
    # get arguments
    arg = trigger.group(3)

    if arg is None:
        if bot.memory['rss']['del_by_id']:
            bot.say('syntax: {}{} <id>|<name>'.format(bot.config.core.prefix, trigger.group(1)))
        else:
            bot.say('syntax: {}{} <name>'.format(bot.config.core.prefix, trigger.group(1)))
        return NOLIMIT

    # check if arg is a number
    try:
        int(arg)
    except ValueError:
        # arg is not a number: name
        __delFeedByName(bot, arg)
    else:
        # arg is a number: id
        if not bot.memory['rss']['del_by_id']:
            # subtract 1 from id argument as rsslist starts counting at 1 and not at 0
            bot.say('please use ".{} {}" to delete feed with the current id {}'.format(trigger.group(1), __getNameByIndex(bot, int(arg) - 1), arg))
            return NOLIMIT

        # subtract 1 from id argument as rsslist starts counting at 1 and not at 0
        __delFeedByIndex(bot, int(arg) - 1)

    __config_save(bot)

    return NOLIMIT

# shoot yourself in the feet
@require_privmsg
@require_admin
@commands('rssdelallfeeds')
def rssdeleteallfeeds(bot, trigger):
    # check number of parameters
    if not trigger.group(2) is None:
        bot.say('syntax: {}{}'.format(bot.config.core.prefix, trigger.group(1)))
        return NOLIMIT

    bot.memory['rss']['feeds'].clear()
    bot.say('all rss feeds deleted successfully')

    __config_save(bot)

    return NOLIMIT

@require_admin
@commands('rssget')
def rssget(bot, trigger):
    # check number of parameters
    if trigger.group(3) is None or (trigger.group(4) and trigger.group(4) != 'all') or trigger.group(5):
        bot.say('syntax: {}{} <name> [<scope>]'.format(bot.config.core.prefix, trigger.group(1)))
        return NOLIMIT

    # if chatty is True then the bot will post feed items to a channel
    chatty = False

    name = trigger.group(3)

    if not __feedExists(bot, name):
        bot.say('feed {} doesn\'t exist'.format(name))
        return NOLIMIT

    if (trigger.group(4) and trigger.group(4) == 'all'):
        chatty = True

    __updateFeed(bot, name, chatty)

    return NOLIMIT

@require_admin
@commands('rssjoin')
def rssjoin(bot, trigger):
    # check number of parameters
    if not trigger.group(2) is None:
        bot.say('syntax: {}{}'.format(bot.config.core.prefix, trigger.group(1)))
        return NOLIMIT

    for feed in bot.memory['rss']['feeds']:
        bot.join(feed['channel'])

    if bot.memory['rss']['monitoring_channel']:
        bot.join(bot.memory['rss']['monitoring_channel'])

    __config_save(bot)

@require_admin
@commands('rsslist')
def rsslist(bot, trigger):
    # check number of parameters
    if not trigger.group(4) is None:
        bot.say('syntax: {}{} [<channel>]'.format(bot.config.core.prefix, trigger.group(1)))
        return NOLIMIT

    channel = trigger.group(3)

    # check that channel starts with #
    if channel and not channel.startswith('#'):
        bot.say('channel "{}" must begin with a "#"'.format(channel))
        return NOLIMIT

    feeds = bot.memory['rss']['feeds']
    for feed in feeds:
        if channel:
            if channel != feed['channel']:
                continue
        bot.say('{}: {} {} {}'.format(feeds.index(feed) + 1, feed['channel'], feed['name'], feed['url']))
    return NOLIMIT

@interval(60)
def __update(bot):
    feeds = bot.memory['rss']['feeds']
    for feed in feeds:
        __updateFeed(bot, feed['name'], False)

def __updateFeed(bot, name, chatty):
    feed = __readFeed(bot, name)
    channel = __getChannelByName(bot, name)

    # print new or all items
    for item in reversed(feed['entries']):
        hash = __hashEntry(name + item['title'] + item['link'] + item['summary'])
        if chatty or not hash in bot.memory['rss']['hashes'].get():
            bot.memory['rss']['hashes'].append(hash)
            message = '\u0002[' + name + ']\u000F '
            message += item['title'] + ' \u0002→\u000F ' + item['link']
            bot.say(message, channel)

    # write config to disk after new hashes have been calculated
    __config_save(bot)

def __readFeed(bot, name):
    try:
        url = __getUrlByName(bot, name)
        if url is None:
            raise Exception
    except:
        bot.say('url of feed "{}" couldn\'t be read!'.format(name), bot.memory['rss']['monitoring_channel'])
        return NOLIMIT

    try:
        feed = feedparser.parse(url)
    except:
        bot.say('error reading feed "{}"'.format(url), bot.memory['rss']['monitoring_channel'])
        return NOLIMIT
    return feed

# read config from disk to memory
def __config_read(bot):
    # read hashes from database to memory
    __readHashesFromDatabase(bot)

    # read feeds from config file
    if bot.config.rss.feeds and bot.config.rss.feeds[0]:
        for feed in bot.config.rss.feeds:
            # split feed line by spaces
            atoms = feed.split(' ')
            bot.memory['rss']['feeds'].append({'channel': atoms[0], 'name': atoms[1], 'url': atoms[2]})

    # read del_by_id from config file
    if bot.config.rss.del_by_id:
        bot.memory['rss']['del_by_id'] = bot.config.rss.del_by_id

    # read monitoring_channel from config file
    if bot.config.rss.monitoring_channel:
        bot.memory['rss']['monitoring_channel'] = bot.config.rss.monitoring_channel

# save config from memory to disk
def __config_save(bot):
    if not bot.memory['rss']['feeds']:
        return NOLIMIT

    # save hashes from memory to database
    __saveHashesToDatabase(bot)

    # we want no more than MAX_HASHES in our database
    __removeOldHashesFromDatabase(bot)

    # save monitoring_channel to config file
    bot.config.rss.monitoring_channel = bot.memory['rss']['monitoring_channel']

    # flatten feeds for config file
    feeds = []
    for feed in bot.memory['rss']['feeds']:
        feeds.append(feed['channel'] + ' ' + feed['name'] + ' ' + feed['url'])
    bot.config.rss.feeds = [",".join(feeds)]

    # save channels to config file
    channels = bot.config.core.channels
    for feed in bot.memory['rss']['feeds']:
        if not feed['channel'] in channels:
            bot.config.core.channels += [feed['channel']]

    try:
        # save config file
        bot.config.save()
    except:
        print('Unable to save config to disk!')
        bot.debug('rss', 'Unable to save config to disk!', 'always')

def __readHashesFromDatabase(bot):
    sql_hashes = 'SELECT * FROM hashes'
    hashes = bot.db.execute(sql_hashes).fetchall()

    # each hash in hashes consists of
    # hash[0]: id
    # hash[1]: md5 hash
    for hash in hashes:
        bot.memory['rss']['hashes'].append(hash[1])

def __saveHashesToDatabase(bot):
    hashes = bot.memory['rss']['hashes'].get()

    # INSERT OR IGNORE is the short form of INSERT ON CONFLICT IGNORE
    sql_save_hashes = 'INSERT OR IGNORE INTO hashes VALUES (NULL,?)'
    for hash in hashes:
        try:
            bot.db.execute(sql_save_hashes, (hash,))
        except:
            # if we have concurrent feed update threads then a database lock may occur
            # this is no problem as the ring buffer will be saved during the next feed update
            pass

def __removeOldHashesFromDatabase(bot):
    # make sure the database has no more than MAX_HASHES rows
    # get the number of rows
    sql_count_hashes = 'SELECT count(*) FROM hashes'
    rows = bot.db.execute(sql_count_hashes).fetchall()[0][0]

    if rows > MAX_HASHES:

        # calculate number of rows to delete in table hashes
        delete_rows = rows - MAX_HASHES

        # prepare sqlite statement to figure out
        # the ids of those hashes which should be deleted
        sql_first_hashes = 'SELECT id FROM hashes ORDER BY hashes.id LIMIT (?)'

        # loop over the hashes which should be deleted
        for row in bot.db.execute(sql_first_hashes, str(delete_rows)).fetchall():

            # delete old hashes from database
            sql_delete_hashes = 'DELETE FROM hashes WHERE hashes.id = (?)'
            bot.db.execute(sql_delete_hashes, (str(row[0]),))

def __delFeedByIndex(bot, index):
    # read url of feed in order to give feedback after the feed has been deleted
    try:
        url = __getUrlByIndex(bot, index)
    except:
        bot.say('feed number "{}" doesn\'t exist!'.format(index))
        return NOLIMIT

    # delete feed
    try:
        if bot.memory['rss']['feeds'][index]:
            del((bot.memory['rss']['feeds'])[index])
            bot.say('rss feed "{}" deleted successfully'.format(url))
    except:
        bot.say('unable to delete feed "{}": feed number doesn\'t exist!'.format(index))

def __delFeedByName(bot, name):
    index = __getIndexByName(bot, name)
    __delFeedByIndex(bot, index)

def __getChannelByName(bot, name):
    feeds = bot.memory['rss']['feeds']
    for feed in feeds:
        if feed['name'] == name:
            return feed['channel']

def __getUrlByName(bot, name):
    feeds = bot.memory['rss']['feeds']
    for feed in feeds:
        if feed['name'] == name:
            return feed['url']

def __getIndexByName(bot, name):
    feeds = bot.memory['rss']['feeds']
    for feed in feeds:
        if feed['name'] == name:
            return feeds.index(feed)

def __getNameByIndex(bot, index):
    return bot.memory['rss']['feeds'][index]['name']

def __getUrlByIndex(bot, index):
    return bot.memory['rss']['feeds'][index]['url']

def __hashEntry(entry):
    return hashlib.md5(entry.encode('utf-8')).hexdigest()

def __feedExists(bot, name):
    feeds = bot.memory['rss']['feeds']
    for feed in feeds:
        if feed['name'] == name:
            return True
    return False

# Implementing a Ring Buffer
# https://www.safaribooksonline.com/library/view/python-cookbook/0596001673/ch05s19.html
class RingBuffer:
    """ class that implements a not-yet-full buffer """
    def __init__(self,size_max):
        self.max = size_max
        self.index = 0
        self.data = []

    class __Full:
        """ class that implements a full buffer """
        def append(self, x):
            """ Append an element overwriting the oldest one. """
            self.data[self.cur] = x
            self.cur = (self.cur+1) % self.max
        def get(self):
            """ return list of elements in correct order """
            return self.data[self.cur:]+self.data[:self.cur]

    def append(self,x):
        """ append an element at the end of the buffer """
        self.data.append(x)
        if len(self.data) == self.max:
            self.cur = 0
            # Permanently change self's class from non-full to full
            self.__class__ = self.__Full

    def get(self):
        """ return a list of elements from the oldest to the newest. """
        return self.data
<commit_msg>Lower MAX_HASHES to 350<commit_after>from __future__ import unicode_literals
import feedparser
import hashlib
from urllib.request import urlopen
from sopel.tools import SopelMemory
from sopel.module import commands, interval, NOLIMIT, require_privmsg, require_admin
from sopel.config.types import StaticSection, ListAttribute, ValidatedAttribute

MAX_HASHES = 350

class RSSSection(StaticSection):
    del_by_id = ListAttribute('del_by_id', default=False)
    feeds = ListAttribute('feeds', default=[])
    hashes = ListAttribute('hashes', default=[])
    monitoring_channel = ValidatedAttribute('monitoring_channel', default='')

def setup(bot):
    bot.config.define_section('rss', RSSSection)
    bot.memory['rss'] = SopelMemory()
    bot.memory['rss']['del_by_id'] = False
    bot.memory['rss']['feeds'] = []
    bot.memory['rss']['hashes'] = RingBuffer(MAX_HASHES)
    bot.memory['rss']['monitoring_channel'] = ''

    # check if a tables named hashes exists
    sql_check_table = "SELECT name FROM sqlite_master WHERE type='table' AND name='hashes'"
    result = bot.db.execute(sql_check_table).fetchall()

    # create table hashes in sqlite3 database provided by the sopel framework
    # use UNIQUE for column hash to minimize database writes by using
    # INSERT OR IGNORE (which is an abbreviation for INSERT ON CONFLICT IGNORE)
    if not result:
        sql_create_table = 'CREATE TABLE hashes (id INTEGER PRIMARY KEY, hash VARCHAR(32) UNIQUE)'
        bot.db.execute(sql_create_table)

    # read config from disk to memory
    __config_read(bot)

def configure(config):
    config.define_section('rss', RSSSection)
    config.rss.configure_setting('del_by_id', 'allow to delete feeds by index. this is potentially dangerous as the index of the remaining feeds may change after one feed has been deleted')
    config.rss.configure_setting('feeds', 'comma separated strings consisting of channel, name, url separated by spaces')
    config.rss.configure_setting('hashes', 'comma separated strings consisting of hashes of rss feed entries')
    config.rss.configure_setting('monitoring_channel', 'channel in which the bot will report errors')

def shutdown(bot):
    print('Shutting down!')
    bot.debug('rss', 'Shutting down!', 'always')

    # write config from memory to disk
    __config_save(bot)

@require_admin
@commands('rssadd')
def rssadd(bot, trigger):
    # check number of parameters
    for i in range(2,6):
        if trigger.group(i) is None:
            bot.say('syntax: {}{} <channel> <name> <url>'.format(bot.config.core.prefix, trigger.group(1)))
            return NOLIMIT

    # get arguments
    channel = trigger.group(3)
    name = trigger.group(4)
    url = trigger.group(5)

    # check that feed name is not a number
    try:
        int(name)
    except ValueError:
        pass
    else:
        bot.say('feed name "{}" is invalid, it has to contain at least one letter'.format(name))
        return NOLIMIT

    # check that feed name is unique
    for feed in bot.memory['rss']['feeds']:
        if name == feed['name']:
            bot.say('feed name "{}" is already in use, please choose a different one'.format(name))
            return NOLIMIT

    # check that channel starts with #
    if not channel.startswith('#'):
        bot.say('channel "{}" must begin with a "#"'.format(channel))
        return NOLIMIT

    # check that feed url is online
    try:
        with urlopen(url) as f:
            if f.status == 200:
                # save config to memory
                bot.memory['rss']['feeds'].append({'channel':channel, 'name':name, 'url':url})
                bot.say('rss feed "{}" added successfully'.format(url))
                bot.join(channel)
    except:
        bot.say('unable to add feed "{}": invalid url! syntax: .{} <channel> <name> <url>'.format(url, trigger.group(1)))
        return NOLIMIT

    __config_save(bot)

    return NOLIMIT

@require_admin
@commands('rssdel')
def rssdel(bot, trigger):
    # get arguments
    arg = trigger.group(3)

    if arg is None:
        if bot.memory['rss']['del_by_id']:
            bot.say('syntax: {}{} <id>|<name>'.format(bot.config.core.prefix, trigger.group(1)))
        else:
            bot.say('syntax: {}{} <name>'.format(bot.config.core.prefix, trigger.group(1)))
        return NOLIMIT

    # check if arg is a number
    try:
        int(arg)
    except ValueError:
        # arg is not a number: name
        __delFeedByName(bot, arg)
    else:
        # arg is a number: id
        if not bot.memory['rss']['del_by_id']:
            # subtract 1 from id argument as rsslist starts counting at 1 and not at 0
            bot.say('please use ".{} {}" to delete feed with the current id {}'.format(trigger.group(1), __getNameByIndex(bot, int(arg) - 1), arg))
            return NOLIMIT

        # subtract 1 from id argument as rsslist starts counting at 1 and not at 0
        __delFeedByIndex(bot, int(arg) - 1)

    __config_save(bot)

    return NOLIMIT

# shoot yourself in the feet
@require_privmsg
@require_admin
@commands('rssdelallfeeds')
def rssdeleteallfeeds(bot, trigger):
    # check number of parameters
    if not trigger.group(2) is None:
        bot.say('syntax: {}{}'.format(bot.config.core.prefix, trigger.group(1)))
        return NOLIMIT

    bot.memory['rss']['feeds'].clear()
    bot.say('all rss feeds deleted successfully')

    __config_save(bot)

    return NOLIMIT

@require_admin
@commands('rssget')
def rssget(bot, trigger):
    # check number of parameters
    if trigger.group(3) is None or (trigger.group(4) and trigger.group(4) != 'all') or trigger.group(5):
        bot.say('syntax: {}{} <name> [<scope>]'.format(bot.config.core.prefix, trigger.group(1)))
        return NOLIMIT

    # if chatty is True then the bot will post feed items to a channel
    chatty = False

    name = trigger.group(3)

    if not __feedExists(bot, name):
        bot.say('feed {} doesn\'t exist'.format(name))
        return NOLIMIT

    if (trigger.group(4) and trigger.group(4) == 'all'):
        chatty = True

    __updateFeed(bot, name, chatty)

    return NOLIMIT

@require_admin
@commands('rssjoin')
def rssjoin(bot, trigger):
    # check number of parameters
    if not trigger.group(2) is None:
        bot.say('syntax: {}{}'.format(bot.config.core.prefix, trigger.group(1)))
        return NOLIMIT

    for feed in bot.memory['rss']['feeds']:
        bot.join(feed['channel'])

    if bot.memory['rss']['monitoring_channel']:
        bot.join(bot.memory['rss']['monitoring_channel'])

    __config_save(bot)

@require_admin
@commands('rsslist')
def rsslist(bot, trigger):
    # check number of parameters
    if not trigger.group(4) is None:
        bot.say('syntax: {}{} [<channel>]'.format(bot.config.core.prefix, trigger.group(1)))
        return NOLIMIT

    channel = trigger.group(3)

    # check that channel starts with #
    if channel and not channel.startswith('#'):
        bot.say('channel "{}" must begin with a "#"'.format(channel))
        return NOLIMIT

    feeds = bot.memory['rss']['feeds']
    for feed in feeds:
        if channel:
            if channel != feed['channel']:
                continue
        bot.say('{}: {} {} {}'.format(feeds.index(feed) + 1, feed['channel'], feed['name'], feed['url']))
    return NOLIMIT

@interval(60)
def __update(bot):
    feeds = bot.memory['rss']['feeds']
    for feed in feeds:
        __updateFeed(bot, feed['name'], False)

def __updateFeed(bot, name, chatty):
    feed = __readFeed(bot, name)
    channel = __getChannelByName(bot, name)

    # print new or all items
    for item in reversed(feed['entries']):
        hash = __hashEntry(name + item['title'] + item['link'] + item['summary'])
        if chatty or not hash in bot.memory['rss']['hashes'].get():
            bot.memory['rss']['hashes'].append(hash)
            message = '\u0002[' + name + ']\u000F '
            message += item['title'] + ' \u0002→\u000F ' + item['link']
            bot.say(message, channel)

    # write config to disk after new hashes have been calculated
    __config_save(bot)

def __readFeed(bot, name):
    try:
        url = __getUrlByName(bot, name)
        if url is None:
            raise Exception
    except:
        bot.say('url of feed "{}" couldn\'t be read!'.format(name), bot.memory['rss']['monitoring_channel'])
        return NOLIMIT

    try:
        feed = feedparser.parse(url)
    except:
        bot.say('error reading feed "{}"'.format(url), bot.memory['rss']['monitoring_channel'])
        return NOLIMIT
    return feed

# read config from disk to memory
def __config_read(bot):
    # read hashes from database to memory
    __readHashesFromDatabase(bot)

    # read feeds from config file
    if bot.config.rss.feeds and bot.config.rss.feeds[0]:
        for feed in bot.config.rss.feeds:
            # split feed line by spaces
            atoms = feed.split(' ')
            bot.memory['rss']['feeds'].append({'channel': atoms[0], 'name': atoms[1], 'url': atoms[2]})

    # read del_by_id from config file
    if bot.config.rss.del_by_id:
        bot.memory['rss']['del_by_id'] = bot.config.rss.del_by_id

    # read monitoring_channel from config file
    if bot.config.rss.monitoring_channel:
        bot.memory['rss']['monitoring_channel'] = bot.config.rss.monitoring_channel

# save config from memory to disk
def __config_save(bot):
    if not bot.memory['rss']['feeds']:
        return NOLIMIT

    # save hashes from memory to database
    __saveHashesToDatabase(bot)

    # we want no more than MAX_HASHES in our database
    __removeOldHashesFromDatabase(bot)

    # save monitoring_channel to config file
    bot.config.rss.monitoring_channel = bot.memory['rss']['monitoring_channel']

    # flatten feeds for config file
    feeds = []
    for feed in bot.memory['rss']['feeds']:
        feeds.append(feed['channel'] + ' ' + feed['name'] + ' ' + feed['url'])
    bot.config.rss.feeds = [",".join(feeds)]

    # save channels to config file
    channels = bot.config.core.channels
    for feed in bot.memory['rss']['feeds']:
        if not feed['channel'] in channels:
            bot.config.core.channels += [feed['channel']]

    try:
        # save config file
        bot.config.save()
    except:
        print('Unable to save config to disk!')
        bot.debug('rss', 'Unable to save config to disk!', 'always')

def __readHashesFromDatabase(bot):
    sql_hashes = 'SELECT * FROM hashes'
    hashes = bot.db.execute(sql_hashes).fetchall()

    # each hash in hashes consists of
    # hash[0]: id
    # hash[1]: md5 hash
    for hash in hashes:
        bot.memory['rss']['hashes'].append(hash[1])

def __saveHashesToDatabase(bot):
    hashes = bot.memory['rss']['hashes'].get()

    # INSERT OR IGNORE is the short form of INSERT ON CONFLICT IGNORE
    sql_save_hashes = 'INSERT OR IGNORE INTO hashes VALUES (NULL,?)'
    for hash in hashes:
        try:
            bot.db.execute(sql_save_hashes, (hash,))
        except:
            # if we have concurrent feed update threads then a database lock may occur
            # this is no problem as the ring buffer will be saved during the next feed update
            pass

def __removeOldHashesFromDatabase(bot):
    # make sure the database has no more than MAX_HASHES rows
    # get the number of rows
    sql_count_hashes = 'SELECT count(*) FROM hashes'
    rows = bot.db.execute(sql_count_hashes).fetchall()[0][0]

    if rows > MAX_HASHES:

        # calculate number of rows to delete in table hashes
        delete_rows = rows - MAX_HASHES

        # prepare sqlite statement to figure out
        # the ids of those hashes which should be deleted
        sql_first_hashes = 'SELECT id FROM hashes ORDER BY hashes.id LIMIT (?)'

        # loop over the hashes which should be deleted
        for row in bot.db.execute(sql_first_hashes, str(delete_rows)).fetchall():

            # delete old hashes from database
            sql_delete_hashes = 'DELETE FROM hashes WHERE hashes.id = (?)'
            bot.db.execute(sql_delete_hashes, (str(row[0]),))

def __delFeedByIndex(bot, index):
    # read url of feed in order to give feedback after the feed has been deleted
    try:
        url = __getUrlByIndex(bot, index)
    except:
        bot.say('feed number "{}" doesn\'t exist!'.format(index))
        return NOLIMIT

    # delete feed
    try:
        if bot.memory['rss']['feeds'][index]:
            del((bot.memory['rss']['feeds'])[index])
            bot.say('rss feed "{}" deleted successfully'.format(url))
    except:
        bot.say('unable to delete feed "{}": feed number doesn\'t exist!'.format(index))

def __delFeedByName(bot, name):
    index = __getIndexByName(bot, name)
    __delFeedByIndex(bot, index)

def __getChannelByName(bot, name):
    feeds = bot.memory['rss']['feeds']
    for feed in feeds:
        if feed['name'] == name:
            return feed['channel']

def __getUrlByName(bot, name):
    feeds = bot.memory['rss']['feeds']
    for feed in feeds:
        if feed['name'] == name:
            return feed['url']

def __getIndexByName(bot, name):
    feeds = bot.memory['rss']['feeds']
    for feed in feeds:
        if feed['name'] == name:
            return feeds.index(feed)

def __getNameByIndex(bot, index):
    return bot.memory['rss']['feeds'][index]['name']

def __getUrlByIndex(bot, index):
    return bot.memory['rss']['feeds'][index]['url']

def __hashEntry(entry):
    return hashlib.md5(entry.encode('utf-8')).hexdigest()

def __feedExists(bot, name):
    feeds = bot.memory['rss']['feeds']
    for feed in feeds:
        if feed['name'] == name:
            return True
    return False

# Implementing a Ring Buffer
# https://www.safaribooksonline.com/library/view/python-cookbook/0596001673/ch05s19.html
class RingBuffer:
    """ class that implements a not-yet-full buffer """
    def __init__(self,size_max):
        self.max = size_max
        self.index = 0
        self.data = []

    class __Full:
        """ class that implements a full buffer """
        def append(self, x):
            """ Append an element overwriting the oldest one. """
            self.data[self.cur] = x
            self.cur = (self.cur+1) % self.max
        def get(self):
            """ return list of elements in correct order """
            return self.data[self.cur:]+self.data[:self.cur]

    def append(self,x):
        """ append an element at the end of the buffer """
        self.data.append(x)
        if len(self.data) == self.max:
            self.cur = 0
            # Permanently change self's class from non-full to full
            self.__class__ = self.__Full

    def get(self):
        """ return a list of elements from the oldest to the newest. """
        return self.data
<|endoftext|>


<commit_before>import ui

if __name__ == "__main__":
	ui.main()
<commit_msg>RUN THIS TO RUN PROGRAM<commit_after>import src.ui

if __name__ == "__main__":
	ui.main()
<|endoftext|>


<commit_before>#!/usr/bin/python

from PyQt4 import QtCore, QtGui
from PyQt4.QtCore import SIGNAL
from UI.Badge import Ui_MainWindow
from src.GpioInputMonitor import IPMonitor
from src.Threads import UART_ConsoleReadThread
import Adafruit_GPIO as GPIO
import Adafruit_GPIO.FT232H as FT232H
import serial,os,fnmatch,sys,subprocess

class BadgeMain(Ui_MainWindow):
        def __init__(self,dialog,parent=None):
                Ui_MainWindow.__init__(self)
		self.ser=serial.Serial()
                self.setupUi(dialog)
		self.UART_getports()
		self.pushButton_UartRefresh.clicked.connect(self.UART_getports)
                self.pushButton_UartConnect.clicked.connect(self.UART_connect)
		self.lineEdit_UartInput.returnPressed.connect(self.UART_send)
		self.pushButton_SpiRun.clicked.connect(self.SPI_run)
		self.SPI_process = QtCore.QProcess()
		self.SPI_process.readyRead.connect(self.SPI_dataReady)
		self.ft232h=0
 	        self.checkBox_d0.clicked.connect(lambda: self.GPIO_handler(0))
                self.checkBox_d1.clicked.connect(lambda: self.GPIO_handler(1))
                self.checkBox_d2.clicked.connect(lambda: self.GPIO_handler(2))
                self.checkBox_d3.clicked.connect(lambda: self.GPIO_handler(3))
                self.checkBox_d4.clicked.connect(lambda: self.GPIO_handler(4))
                self.checkBox_d5.clicked.connect(lambda: self.GPIO_handler(5))
                self.checkBox_d6.clicked.connect(lambda: self.GPIO_handler(6))
                self.checkBox_d7.clicked.connect(lambda: self.GPIO_handler(7))
		self.InputMonitor=None
                self.pushButton_GpioStartInputMonitor.clicked.connect(self.GPIO_startmonitor)

	def UART_getports(self):
		#Function checks for connected usb devices
        	print("[*] UART_getport invoked ")
        	path="/dev/"
        	pattern="ttyUSB*"
        	result=[]
        	for root, dirs, files in os.walk(path):
        	        for name in files:
        	                if fnmatch.fnmatch(name, pattern):
        	                        result.append(os.path.join(root, name))
        	self.comboBox_UartPort.clear()
		self.comboBox_UartPort.addItems(result)

	def UART_connect(self):
		#Connects to the device who's port address is given by ComboBox_Port, disconnects if already connected
		print("[*] UART_Connect invoked ")
		ser_port=str(self.comboBox_UartPort.currentText())
		baud_rate=int(str(self.comboBox_UartBaud.currentText()))
		self.ser.port=ser_port
		self.ser.baudrate=baud_rate
		try:
			if(str(self.ser.isOpen())=="False"):
				self.ser.open()
				self.lineEdit_UartInput.enabledChange(True)
				print("[*] UART_Connect executed Successfully ")
				self.pushButton_UartConnect.setText("Disconnect")
				print("[*] Serial port opened ")
				if(self.ser.isOpen()):
			                self.uartReadThread=UART_ConsoleReadThread(self.ser)
					QtCore.QObject.connect(self.uartReadThread,QtCore.SIGNAL("update_console(QString)"), self.UART_read)
					print("[*] Starting UARTConsoleReadThread ")
					self.uartReadThread.start()
			else:
				print("[*] Stopping UART_ConsoleReadThread ")
				self.uartReadThread.close()
				self.ser.close()
                                self.lineEdit_UartInput.enabledChange(False)
                                self.pushButton_UartConnect.setText("Connect")
				print("[*] Serial port closed ")
		except Exception as e:
			print("[*] UART_Connect Failed ->  "+str(e))
			self.textEdit_UartConsole.append("[*] Connection Failed ")
		return

	def UART_read(self, QString):
		if(len(str(QString))>0):
			self.textEdit_UartConsole.insertPlainText(str(QString))
		self.textEdit_UartConsole.moveCursor(QtGui.QTextCursor.End)

	def UART_send(self):
		#sends the contents of lineEdit_UartInput to the connected device
		print("[*] UART_txsend invoked ")
		terminator=""
		command=self.lineEdit_UartInput.text()
		if(command=="clear"):
			self.textEdit_UartConsole.clear()
			command=""
		elif(str(self.comboBox_UartTerminator.currentText())=="No line ending"):
			terminator=""
		elif(str(self.comboBox_UartTerminator.currentText())=="Carriage Return"):
			terminator="\r"
		elif(str(self.comboBox_UartTerminator.currentText())=="New Line"):
			terminator="\n"
		elif(str(self.comboBox_UartTerminator.currentText())=="Both CR + NL"):
			terminator="\r\n"
		self.ser.write(str((command+terminator)).encode())
		self.ser.write(terminator.encode())
		self.lineEdit_UartInput.setText("")

	def SPI_dataReady(self):
		cursor=self.textEdit_SpiConsole.textCursor()
		cursor.movePosition(cursor.End)
		cursor.insertText(str(self.SPI_process.readAll()))
		self.textEdit_SpiConsole.ensureCursorVisible()

	def SPI_run(self):
		print("[*] SPI_RunCmds Executing ")
		self.textEdit_SpiConsole.append("----------------------------------------------------------------\n")
		filepath=str(self.lineEdit_SpiFilePath.text())
		cmd=str(self.comboBox_SpiOperation.currentText()).strip()
		if cmd=="Find Chip":
			self.SPI_process.start('flashrom',['-p','ft2232_spi:type=232H'])
		elif cmd=="Read":
			self.SPI_process.start('flashrom',['-p','ft2232_spi:type=232H','-r',filepath])
		elif cmd=="Write":
			self.SPI_process.start('flashrom',['-p','ft2232_spi:type=232H','-w',filepath])
		elif cmd=="Erase":
			self.SPI_process.start('flashrom',['-p','ft2232_spi:type=232H','--erase',filepath])

	def GPIO_setup(self):
        	if(self.ft232h==0):
                	try:
				print("[*] Setting up GPIO ")
                        	FT232H.use_FT232H()
                        	self.ft232h = FT232H.FT232H()
				#setting everything as out
				#because leaving then un-
				#initialized confuses the
				#Input Monitor
	        		self.ft232h.setup(0, GPIO.OUT)
        			self.ft232h.setup(1, GPIO.OUT)
        			self.ft232h.setup(2, GPIO.OUT)
        			self.ft232h.setup(3, GPIO.OUT)
        			self.ft232h.setup(4, GPIO.OUT)
        			self.ft232h.setup(5, GPIO.OUT)
        			self.ft232h.setup(6, GPIO.OUT)
       			 	self.ft232h.setup(7, GPIO.OUT)

                	except Exception as e:
                        	print("[*] Error : "+str(e))
                        	exit()

	def GPIO_handler(self,pin):
		self.GPIO_setup()
		pin_combo={0:self.comboBox_d0,1:self.comboBox_d1,2:self.comboBox_d2,3:self.comboBox_d3,4:self.comboBox_d4,5:self.comboBox_d5,6:self.comboBox_d6,7:self.comboBox_d7}
		pin_check={0:self.checkBox_d0,1:self.checkBox_d1,2:self.checkBox_d2,3:self.checkBox_d3,4:self.checkBox_d4,5:self.checkBox_d5,6:self.checkBox_d6,7:self.checkBox_d7}
		mode=pin_check[pin].isChecked()
		if(str(pin_combo[pin].currentText())=="Input"):
			self.ft232h.setup(pin,GPIO.IN)
			print("[*] Pin "+str(pin)+" set as Input")
		elif(str(pin_combo[pin].currentText())=="Output"):
                        print("[*] Pin "+str(pin)+" set as Output")
			self.ft232h.setup(pin,GPIO.OUT)
			if(mode):
				print("[*] Pin "+str(pin)+" : HIGH ")
				self.ft232h.output(pin, GPIO.HIGH)
			else:
				self.ft232h.output(pin, GPIO.LOW)
                                print("[*] Pin "+str(pin)+" : LOW ")

	def GPIO_startmonitor(self):
		if self.InputMonitor is None:
			self.InputMonitor=IPMonitor(self.ft232h)
		self.InputMonitor.show()

if __name__=="__main__":
        app=QtGui.QApplication(sys.argv)
        dialog=QtGui.QMainWindow()
        prog=BadgeMain(dialog)
        dialog.show()
        sys.exit(app.exec_())

<commit_msg>Added I2C Search<commit_after>#!/usr/bin/python

from PyQt4 import QtCore, QtGui
from PyQt4.QtCore import SIGNAL
from UI.Badge import Ui_MainWindow
from src.GpioInputMonitor import IPMonitor
from src.Threads import UART_ConsoleReadThread
import Adafruit_GPIO as GPIO
import Adafruit_GPIO.FT232H as FT232H
import serial,os,fnmatch,sys,subprocess

class BadgeMain(Ui_MainWindow):
        def __init__(self,dialog,parent=None):
                Ui_MainWindow.__init__(self)
		self.ser=serial.Serial()
                self.setupUi(dialog)
		self.UART_getports()
		self.pushButton_UartRefresh.clicked.connect(self.UART_getports)
                self.pushButton_UartConnect.clicked.connect(self.UART_connect)
		self.lineEdit_UartInput.returnPressed.connect(self.UART_send)
		self.pushButton_SpiRun.clicked.connect(self.SPI_run)
		self.SPI_process = QtCore.QProcess()
		self.SPI_process.readyRead.connect(self.SPI_dataReady)
		self.ft232h=0
		self.gpio_init=0
 	        self.checkBox_d0.clicked.connect(lambda: self.GPIO_handler(0))
                self.checkBox_d1.clicked.connect(lambda: self.GPIO_handler(1))
                self.checkBox_d2.clicked.connect(lambda: self.GPIO_handler(2))
                self.checkBox_d3.clicked.connect(lambda: self.GPIO_handler(3))
                self.checkBox_d4.clicked.connect(lambda: self.GPIO_handler(4))
                self.checkBox_d5.clicked.connect(lambda: self.GPIO_handler(5))
                self.checkBox_d6.clicked.connect(lambda: self.GPIO_handler(6))
                self.checkBox_d7.clicked.connect(lambda: self.GPIO_handler(7))
		self.InputMonitor=None
                self.pushButton_GpioStartInputMonitor.clicked.connect(self.GPIO_startmonitor)
		self.pushButton_I2cRun.clicked.connect(self.I2C_run)

	def UART_getports(self):
		#Function checks for connected usb devices
        	print("[*] UART_getport invoked ")
        	path="/dev/"
        	pattern="ttyUSB*"
        	result=[]
        	for root, dirs, files in os.walk(path):
        	        for name in files:
        	                if fnmatch.fnmatch(name, pattern):
        	                        result.append(os.path.join(root, name))
        	self.comboBox_UartPort.clear()
		self.comboBox_UartPort.addItems(result)

	def UART_connect(self):
		#Connects to the device who's port address is given by ComboBox_Port, disconnects if already connected
		print("[*] UART_Connect invoked ")
		ser_port=str(self.comboBox_UartPort.currentText())
		baud_rate=int(str(self.comboBox_UartBaud.currentText()))
		self.ser.port=ser_port
		self.ser.baudrate=baud_rate
		try:
			if(str(self.ser.isOpen())=="False"):
				self.ser.open()
				self.lineEdit_UartInput.enabledChange(True)
				print("[*] UART_Connect executed Successfully ")
				self.pushButton_UartConnect.setText("Disconnect")
				print("[*] Serial port opened ")
				if(self.ser.isOpen()):
			                self.uartReadThread=UART_ConsoleReadThread(self.ser)
					QtCore.QObject.connect(self.uartReadThread,QtCore.SIGNAL("update_console(QString)"), self.UART_read)
					print("[*] Starting UARTConsoleReadThread ")
					self.uartReadThread.start()
			else:
				print("[*] Stopping UART_ConsoleReadThread ")
				self.uartReadThread.close()
				self.ser.close()
                                self.lineEdit_UartInput.enabledChange(False)
                                self.pushButton_UartConnect.setText("Connect")
				print("[*] Serial port closed ")
		except Exception as e:
			print("[*] UART_Connect Failed ->  "+str(e))
			self.textEdit_UartConsole.append("[*] Connection Failed ")
		return

	def UART_read(self, QString):
		if(len(str(QString))>0):
			self.textEdit_UartConsole.insertPlainText(str(QString))
		self.textEdit_UartConsole.moveCursor(QtGui.QTextCursor.End)

	def UART_send(self):
		#sends the contents of lineEdit_UartInput to the connected device
		print("[*] UART_txsend invoked ")
		terminator=""
		command=self.lineEdit_UartInput.text()
		if(command=="clear"):
			self.textEdit_UartConsole.clear()
			command=""
		elif(str(self.comboBox_UartTerminator.currentText())=="No line ending"):
			terminator=""
		elif(str(self.comboBox_UartTerminator.currentText())=="Carriage Return"):
			terminator="\r"
		elif(str(self.comboBox_UartTerminator.currentText())=="New Line"):
			terminator="\n"
		elif(str(self.comboBox_UartTerminator.currentText())=="Both CR + NL"):
			terminator="\r\n"
		self.ser.write(str((command+terminator)).encode())
		self.ser.write(terminator.encode())
		self.lineEdit_UartInput.setText("")

	def SPI_dataReady(self):
		cursor=self.textEdit_SpiConsole.textCursor()
		cursor.movePosition(cursor.End)
		cursor.insertText(str(self.SPI_process.readAll()))
		self.textEdit_SpiConsole.ensureCursorVisible()

	def SPI_run(self):
		print("[*] SPI_RunCmds Executing ")
		self.textEdit_SpiConsole.append("----------------------------------------------------------------\n")
		filepath=str(self.lineEdit_SpiFilePath.text())
		cmd=str(self.comboBox_SpiOperation.currentText()).strip()
		if cmd=="Find Chip":
			self.SPI_process.start('flashrom',['-p','ft2232_spi:type=232H'])
		elif cmd=="Read":
			self.SPI_process.start('flashrom',['-p','ft2232_spi:type=232H','-r',filepath])
		elif cmd=="Write":
			self.SPI_process.start('flashrom',['-p','ft2232_spi:type=232H','-w',filepath])
		elif cmd=="Erase":
			self.SPI_process.start('flashrom',['-p','ft2232_spi:type=232H','--erase',filepath])

	def FTDI_setup(self):
        	if(self.ft232h==0):
                	try:
				print("[*] Enabling Adafruit FTDI ")
                        	FT232H.use_FT232H()
                        	self.ft232h = FT232H.FT232H()

			except Exception as e:
                                print("[*] Error : "+str(e))

	def GPIO_setup(self):
		if(self.gpio_init==0):
			print("[*] Setting up GPIO pins")
			#setting everything as out
			#because leaving then un-
			#initialized confuses the
			#Input Monitor
	        	self.ft232h.setup(0, GPIO.OUT)
        		self.ft232h.setup(1, GPIO.OUT)
        		self.ft232h.setup(2, GPIO.OUT)
        		self.ft232h.setup(3, GPIO.OUT)
        		self.ft232h.setup(4, GPIO.OUT)
        		self.ft232h.setup(5, GPIO.OUT)
        		self.ft232h.setup(6, GPIO.OUT)
       			self.ft232h.setup(7, GPIO.OUT)
			self.gpio_init=1

	def GPIO_handler(self,pin):
		self.FTDI_setup()
		self.GPIO_setup()
		pin_combo={0:self.comboBox_d0,1:self.comboBox_d1,2:self.comboBox_d2,3:self.comboBox_d3,4:self.comboBox_d4,5:self.comboBox_d5,6:self.comboBox_d6,7:self.comboBox_d7}
		pin_check={0:self.checkBox_d0,1:self.checkBox_d1,2:self.checkBox_d2,3:self.checkBox_d3,4:self.checkBox_d4,5:self.checkBox_d5,6:self.checkBox_d6,7:self.checkBox_d7}
		mode=pin_check[pin].isChecked()
		if(str(pin_combo[pin].currentText())=="Input"):
			self.ft232h.setup(pin,GPIO.IN)
			print("[*] Pin "+str(pin)+" set as Input")
		elif(str(pin_combo[pin].currentText())=="Output"):
                        print("[*] Pin "+str(pin)+" set as Output")
			self.ft232h.setup(pin,GPIO.OUT)
			if(mode):
				print("[*] Pin "+str(pin)+" : HIGH ")
				self.ft232h.output(pin, GPIO.HIGH)
			else:
				self.ft232h.output(pin, GPIO.LOW)
                                print("[*] Pin "+str(pin)+" : LOW ")

	def GPIO_startmonitor(self):
		if self.InputMonitor is None:
			self.InputMonitor=IPMonitor(self.ft232h)
		self.InputMonitor.show()

	def I2C_run(self):
                self.textEdit_I2cConsole.append("[*] Scanning all I2C addresses. ")
		count=0
		print(count)
		self.FTDI_setup()
		for address in range(127):
        		if address <= 7 or address >= 120:
                		continue
        		i2c = FT232H.I2CDevice(self.ft232h, address)
        		if i2c.ping():
				count=count+1
                		self.textEdit_I2cConsole.append("Found I2C device at address 0x{0:02X}".format(address))
		self.textEdit_I2cConsole.append("[*] Found "+str(count)+" devices. ")

if __name__=="__main__":
        app=QtGui.QApplication(sys.argv)
        dialog=QtGui.QMainWindow()
        prog=BadgeMain(dialog)
        dialog.show()
        sys.exit(app.exec_())

<|endoftext|>


<commit_before>#! /usr/bin/env python
# -*- coding=utf-8 -*-

import _init
import random
# import click
import StoreData

def choice_module():
    dec = raw_input("吃什么？（输入1）录入新选择（输入2）查询现有选择（输入3）") or "None"
    dec = int(dec)
    return dec

def print_m(result):
    if result:
        print(result)
    else:
        print("出错了")

def main(module):

    if module == 1:
        try:
            i = random.randint(0, len(StoreData.store_list)-1)
            result = "推荐 {0}！\n".format(StoreData.store_list[i][1].encode('utf-8'))
            if StoreData.store_list[i][2]:
                result += "地址为 {0}！".format(StoreData.store_list[i][2].encode('utf-8'))
        except IndexError:
            print(i)
            result = "貌似没有可供选择的店呢，新加点店面嗷"

    if module == 2:
        StoreData.input_store_name()
        result = "添加成功"

    if module == 3:
        result = ""
        if len(StoreData.store_list) == 0:
            result = "貌似没有可供选择的店呢，新加点店面嗷"
        for i in range(len(StoreData.store_list)):
            result += '''编号：{0}  店名：{1}  地址：{2}\n'''  \
            .format(StoreData.all_store[i][0].encode('utf-8'),
                StoreData.all_store[i][1].encode('utf-8'),
                StoreData.all_store[i][2].encode('utf-8'))

    return result

if __name__ == '__main__':
    print_m(main(choice_module()))<commit_msg>fix bug<commit_after>#! /usr/bin/env python
# -*- coding=utf-8 -*-

import _init
import random
# import click
import StoreData

def choice_module():
    dec = raw_input("吃什么？（输入1）录入新选择（输入2）查询现有选择（输入3）") or "None"
    dec = int(dec)
    return dec

def print_m(result):
    if result:
        print(result)
    else:
        print("出错了")

def main(module):

    if module == 1:
        try:
            i = random.randint(0, len(StoreData.store_list)-1)
            result = "推荐 {0}！\n".format(StoreData.store_list[i][1].encode('utf-8'))
            if StoreData.store_list[i][2]:
                result += "地址为 {0}！".format(StoreData.store_list[i][2].encode('utf-8'))
        except ValueError:
            result = "貌似没有可供选择的店呢，新加点店面嗷"

    if module == 2:
        StoreData.input_store_name()
        result = "添加成功"

    if module == 3:
        result = ""
        if len(StoreData.store_list) == 0:
            result = "貌似没有可供选择的店呢，新加点店面嗷"
        for i in range(len(StoreData.store_list)):
            result += '''编号：{0}  店名：{1}  地址：{2}\n'''  \
            .format(StoreData.all_store[i][0].encode('utf-8'),
                StoreData.all_store[i][1].encode('utf-8'),
                StoreData.all_store[i][2].encode('utf-8'))

    return result

if __name__ == '__main__':
    print_m(main(choice_module()))<|endoftext|>