コード例 #1
0
 def statistics(self, output='descriptive'):
     stat_log = log.getLogger('statistics', '{message}')
     res_count = namedtuple('Results', ['tweet', 'follow'])
     res_count.tweet = namedtuple('Tweets', ['correct', 'missed', 'bad_content'])
     res_count.tweet.correct = 0
     res_count.tweet.missed = 0
     res_count.tweet.bad_content = 0
     stat_log.debug("    RESULTS")
     for t in self.mock:
         was_replied_to = t.id in self.replies
         if t.expected_answer is None:
             if was_replied_to:
                 stat_log.error("Tweet %d falsely answered", t.id)
                 res_count.tweet.missed += 1
             else:
                 res_count.tweet.correct += 1
                 stat_log.info("Tweet %d correctly unanswered", t.id)
             continue
         # expected answer is not None:
         if not was_replied_to:
             res_count.tweet.missed += 1
             stat_log.error("Tweet %d falsely unanswered", t.id)
             continue
         # correctly answered: is it the correct answer?
         if t.expected_answer == self.replies[t.id]:
             res_count.tweet.correct += 1
             stat_log.info("Tweet %d correctly answered with correct answer", t.id)
             continue
         res_count.tweet.bad_content += 1
         stat_log.error("Tweet %d correctly answered, but with wrong answer", t.id)
         stat_log.warning(t.expected_answer)
         stat_log.warning("↑↑↑↑EXPECTED↑↑↑↑  ↓↓↓↓GOT THIS↓↓↓↓")
         stat_log.warning(self.replies[t.id])
     res_count.follow = namedtuple('Following', ['correct', 'wrong'])
     res_count.follow.correct = 0
     res_count.follow.wrong = 0
     for l in User.followers, User.nonfollowers:
         for u in l:
             if u.follows == u.follow_after:
                 stat_log.info("User @%s has correct following behaviour %s",
                               u.screen_name, u.follows)
                 res_count.follow.correct += 1
             else:
                 stat_log.error("User @%s doesn't follow correctly (should %s, does %s)",
                                u.screen_name, u.follow_after, u.follows)
                 res_count.follow.wrong += 1
     self.report_statisctics(stat_log, output, res_count)
     return res_count.tweet.missed + res_count.tweet.bad_content + res_count.follow.wrong
コード例 #2
0
# pylint: disable=C0114

import time
import tweepy
import Persistence.log as log
from Externals.twitter.Api import TwitterBase as BaseApi
log_ = log.getLogger(__name__)


class ReadWrite(BaseApi):
    def tweet_single(self, text, **kwargs):
        """Actually posts text as a new tweet.

        kwargs are passed to tweepy directly.

        Returns:
            - the ID of the newly created tweet if there were no errors (positive)
            - -1 if there was an unknown error
            - -api_code if there was an error with API code api_code

        If api_code is 185 (status update limit), then the program pauses 1 minute and tries again
        (this will be repeated indefinitely) An error message will be logged each time.

        If api_code is neither 185 nor 187 (duplicate tweet), a critical log message will be logged.
        """
        super().tweet_single(text, **kwargs)
        while True:  # catches rate limit
            try:
                new_tweet = self.twit.update_status(text, **kwargs)
                return new_tweet.id
            except tweepy.TweepError as twerror:
コード例 #3
0
#!/usr/bin/python3

"""Read source configuation"""

import json
import Persistence.log as log
from .access import Access
from .datasource import DataSource
from .error import JsonError
log_ = log.getLogger(__name__, fmt='{name}:{levelname} {message}')

class SourceConfig:
    # pylint: disable=R0903
    # pylint: disable=R0902
    _mandatory_fields = (
        'access',
        'data',
        'id',
        'magic_hashtags'
    )

    def __init__(self, filepath):
        self.file = filepath
        with self.file.open() as jsonfile:
            try:
                self.json = json.load(jsonfile)
            except json.JSONDecodeError as jde:
                msg = "{}::{}::{}: JSON object could not be decoded: {}".format(
                    self.file, jde.lineno, jde.colno, jde.msg)
                raise JsonError(msg)
        for mf in SourceConfig._mandatory_fields:
コード例 #4
0
# pylint: disable=C0114

import regex as re
import Persistence.log as log
from .candidate import Candidate
from .result import Result
log_ = log.getLogger(__name__)
follog_ = log.getLogger(__name__ + '.following', '{name} {message}')


def process_tweet(tweet, twitter, database, magic_tags, **kwargs):
    textlist = list(tweet.text)
    for key in ['media', 'urls']:
        if key in tweet.original.entities:
            for ent in tweet.original.entities[key]:
                start = ent['indices'][0]
                end = ent['indices'][1]
                length = end - start
                textlist[start:end] = '_' * length
    tweet.text = "".join(textlist)
    reply = compose_answer(tweet.text, database, tweet.hashtags(magic_tags),
                           kwargs.get('modus', None),
                           kwargs.get('default_magic_tag', 'DS100'))
    if len(reply.strip()) == 0:
        log_.info("No expandable content found")
        return
    twitter.tweet(reply,
                  in_reply_to_status_id=tweet.id,
                  auto_populate_reply_metadata=True)

コード例 #5
0
"""Twitter API including Command line argumentation"""

import configparser
import time
import tweepy

from Externals.Measure import Measure
import Persistence.log as log
log_ = log.getLogger(__name__)
tweet_log_ = log.getLogger('tweet', '{message}')


def set_arguments(ap):
    group = ap.add_argument_group('Twitter API',
                                  description='Configure Twitter API')
    group.add_argument('--config',
                       action='store',
                       help='path to configuration file',
                       required=True)
    group.add_argument('--application',
                       action='store',
                       help='Name of the twitter application',
                       required=True)
    group.add_argument('--user',
                       action='store',
                       help='Name of the user',
                       required=True)
    group.add_argument('--readwrite',
                       action='store_true',
                       help="Don't tweet, only read tweets.",
                       required=False)