def __init__(self): # default initalization TwitterBot.__init__(self) # load image urls from a file self.load_image_urls("images.txt")
def on_follow(self, follower_id): TwitterBot.on_follow(self, follower_id) try: self.store.save_friend((follower_id,)) except pg.IntegrityError: # aborting is harmless, most likely an unfollow/refollow self.log("tried to add duplicate twitter friend %s" % follower_id)
def main(): from argparse import ArgumentParser arg_parser = ArgumentParser() arg_parser.add_argument('--test', help='Test mode, don''t tweet', action='store_true', default=False) args = arg_parser.parse_args() import settings from twitterbot import TwitterBot bot = TwitterBot(settings, args) bot.run()
class TestTwitterBot(unittest.TestCase): def setUp(self): self.bot = TwitterBot(config_file='tests/config_test.json') def test_oath_config(self): self.assertEqual(self.bot.oauth_config, ("REPLACE ME", "REPLACE ME", "REPLACE ME", "REPLACE ME")) @mock.patch('util.generate_text', return_value='hello') @mock.patch('twython.Twython.update_status') def test_update_status(self, update_status_mock, generate_text_mock): self.bot.post_update() generate_text_mock.assert_called_with(limit_characters=140) update_status_mock.assert_called_with(status='hello')
def main(): requestJson = request.get_json() #print(json.dumps(requestJson, indent=4, sort_keys=True)) if 'tweet_create_events' in requestJson.keys(): mentioned_name = requestJson['tweet_create_events'][0]['entities'][0][ "user_mentions"].get("screen_name") if mentioned_name == "Arkham_bot": replying_to = requestJson['tweet_create_events'][0]['user'][ 'screen_name'] tweet_id = requestJson['tweet_create_events'][0]['id_str'] TwitterBot.reply(replying_to, tweet_id) #elif 'follow_events' in requestJson.keys(): #TwitterBot.follow_back() return ('OK')
def main(): try: now = time() # Construct auth and twitterbot object auth = OAuth(config['access_token'], config['access_secret'], config['consumer_key'], config['consumer_secret']) twitterBot = TwitterBot(auth) # create brainyquote object and load quotes quote = BrainyQuote() quote.load() iter = 0 while True: # Safeguard, just stop running after 1000 iterations if iter >= 1000: break random_quote = quote.randomize() if not quote.exists(random_quote): text, auth = random_quote auth = twitterify(auth) if len(auth) + len(text) > 140: text = text[0:140 - len(auth)] tweet = '%s %s' % (text, auth) if twitterBot.tweet(tweet): quote.save(random_quote) break iter = iter + 1 except Exception as err: Logger("Unhandled exception!: %s" % err) except QuoteException as qerr: Logger("Quote exception in program: %s" % qerr) finally: message = 'Finished running TwitterBot, date: {0}, running time: {1} secs'.format(str(datetime.now()), time() - now) Logger(message)
def repost_replies(account_name): bf = open('.blacklist_%s'%account_name,'a+') blacklist = bf.read().splitlines() bf.close() rp = open('.reposted_%s'%account_name,'a+') reposted = rp.read().splitlines() account = settings.ACCOUNTS.get(account_name) try: logging.info('[%s] Getting last mentions offset'%account_name) bot = TwitterBot(settings.CONSUMER_KEY,settings.CONSUMER_SECRET, account['key'],account['secret']) mentions = [] try: mentions = bot.api.mentions() logging.info('[%s] Got %d mentions'%(account_name,len(mentions))) except Exception,e: logging.error('[%s] Failed to get mentions. %s'%(account_name,e)) for mess in reversed(mentions): try: author = mess.author.screen_name if str(author) in blacklist: logging.debug('[%s] Author %s blacklisted. Skipping.'%(account_name,str(author))) continue if str(mess.id) in reposted: logging.debug('[%s] Message #%s already reposted. Skipping.'%(account_name,str(mess.id))) continue message = mess.text.split(' ') if message[0] != '@%s'%account_name: continue #not a "@reply" trigger = message[1] triggers = dict(account['triggers']) if trigger not in triggers: logging.warning('[%s] Bad message format, sending DM to author'%account_name) bot.dm(author,account['not_triggered']) else: len_params = {'message':'','user':author} mess_len = len(triggers[trigger]%len_params) params = {'message':bot.trim_message(' '.join(message[2:]),mess_len),'user':author} message = triggers[trigger]%params logging.info('[%s] Tweeting message %s'%(account_name,message)) bot.tweet(message) rp.write('%s\n'%mess.id) except Exception,e: logging.error('%s'%e) continue
def update_network(accounts, depth): for account_id in accounts.keys(): print '\tupdating user:'******'\t\tupdating', acc_type, 'account:', acc_username if acc_username == '': continue elif acc_type == TWITTER: crawler = TwitterBot.factory(acc_username, depth=depth) personUris.append(crawler.getUserUri(acc_username)) # create crawlers using user network accounts data crawler.crawlUserNetwork(start_time=sdate) # link resources to each other Resource.unify_all(personUris)
def main(): feed = feedparser.parse( 'https://fedoramagazine.org/feed/') # read the feed try: links = pickle.load(open('tweeted_links', 'rb')) # load posted links except FileNotFoundError: links = set() # no link is posted yet try: bot = TwitterBot(USERNAME, PASSWORD) for entry in feed.entries[::-1]: link = entry.link title = entry.title print(title, link) if link not in links: bot.tweet(title + '\n' + link) links.add(link) bot.quit() # quits and clears the chromedriver from memory finally: pickle.dump(links, open('tweeted_links', 'wb')) # add the posted links to the file
# Import the TwitterBot class from twitterbot import TwitterBot # create a new bot bot = TwitterBot("my_username", "my_secret_password") # tweet bot.tweet("Hello world from python and selenium") # quit the bot and close the chrome window bot.quit()
def generate_word(clean_data): with open(clean_data_file, 'r') as f: for line in f: for word in line.split(): yield word if __name__ == '__main__': logging.info("Initializing bot_data file.") with open(bot_data_file, 'w') as file: json.dump({"last_id_seen": None, "last_reply_id_seen": None}, file) markov = Markov() twitterbot = TwitterBot() logging.info("Connecting to the database.") markov._connect_db() markov.cur.execute( """ SELECT EXISTS(SELECT 1 FROM information_schema.tables \ WHERE table_catalog=%(db_name)s \ AND table_schema='public' \ AND table_name='transition'); """, {'db_name': config.DATABASE_NAME}) table_exists = markov.cur.fetchone()[0] if not table_exists: logging.info("Transition table does not exist. Creating it now...") markov.cur.execute("""
# Get the filename of the response file from the config file. responsefile = config.get(botname, 'responsefile') # Determine which of the microblog classes to instantiate. microblog_type = config.get(botname, 'type') if microblog_type == 'twitter': # Load the Twitter API keys from the config file. api_key = config.get(botname, 'api_key') api_secret = config.get(botname, 'api_secret') access_token = config.get(botname, 'access_token') access_token_secret = config.get(botname, 'access_token_secret') # Instantiate a Twitter bot. bot = TwitterBot(owner, botname, username, password, muc, muclogin, imalive, responsefile, function, api_key, api_secret, access_token, access_token_secret) else: print "No other kinds of microblog bots are defined yet." sys.exit(0) # Connect to the XMPP server and start processing messages. if bot.connect(): bot.process(block=False) else: print "ERROR: Unable to connect to XMPP server." sys.exit(1) # Fin.
continue #not a "@reply" trigger = message[1] triggers = dict(account['triggers']) if trigger not in triggers: logging.warning('[%s] Bad message format, sending DM to author'%account_name) bot.dm(author,account['not_triggered']) else: len_params = {'message':'','user':author} mess_len = len(triggers[trigger]%len_params) params = {'message':bot.trim_message(' '.join(message[2:]),mess_len),'user':author} message = triggers[trigger]%params logging.info('[%s] Tweeting message %s'%(account_name,message)) bot.tweet(message) rp.write('%s\n'%mess.id) except Exception,e: logging.error('%s'%e) continue except Exception,e: logging.error('%s'%e) finally: rp.close() if options.authorize: bot = TwitterBot(settings.CONSUMER_KEY,settings.CONSUMER_SECRET) bot.get_tokens() sys.exit('Bye ;)') if options.repost: for account in options.repost.split(' '): repost_replies(account.strip())
from apscheduler.scheduler import Scheduler from twitterbot import TwitterBot import time from app_config import AppConfig sched = Scheduler() config = AppConfig() bot = TwitterBot(config) bot.send_tweet() @sched.interval_schedule(minutes=120) def timed_job(): bot.send_tweet() sched.start() while True: time.sleep(1)
logging.basicConfig(level=loglevel, format='%(levelname)-8s %(message)s') # Get the filename of the response file from the config file. responsefile = config.get(botname, 'responsefile') # Determine which of the microblog classes to instantiate. microblog_type = config.get(botname, 'type') if microblog_type == 'twitter': # Load the Twitter API keys from the config file. api_key = config.get(botname, 'api_key') api_secret = config.get(botname, 'api_secret') access_token = config.get(botname, 'access_token') access_token_secret = config.get(botname, 'access_token_secret') # Instantiate a Twitter bot. bot = TwitterBot(owner, botname, username, password, muc, muclogin, imalive, responsefile, function, api_key, api_secret, access_token, access_token_secret) else: print "No other kinds of microblog bots are defined yet." sys.exit(0) # Connect to the XMPP server and start processing messages. if bot.connect(): bot.process(block=False) else: print "ERROR: Unable to connect to XMPP server." sys.exit(1) # Fin.
fetchers = [] for i in xrange(feeds_count): # TODO: abstract fetcher_args object fetchers.append(FeedFetcher( feed_url=feeds[i], data_dir=data_dir, cache_dir=cache_dir, cache_feed=cache_feed, verbose=args.verbose, no_cache=args.no_cache)) if args.verbose > 2: print(fetchers) if args.twitter: # TODO: pass in all args twitter_bot = TwitterBot(args.config_file, args.verbose) tweeted_file = open(cp.get('General', 'tweeted'), 'r+') tweeted = set(tweeted_file.read().split('\n')) if args.verbose > 2: print(tweeted) if args.database: # TODO: abstract db_args object host = cp.get('General', 'db_host') user = cp.get('General', 'db_user') cred = cp.get('General', 'db_cred') db = cp.get('General', 'db_name') db_saver = DBSaver(host, user, cred, db, args=args) try: while True:
import tweepy import time from accesskeys import * from twitterbot import TwitterBot # Twitter restricts number of bot activites by 1000 per day as of now. number_of_iterations = 50 # Your query to search and like the tweets. search_query = 'medical%20students' # The SECRECT_KEY, SECRET_TOKEN, ACCESS_KEY, ACESS_TOKEN # can be accessed from https://developer.twitter.com/en/apps bot = TwitterBot(number_of_iterations, SECRECT_KEY, SECRET_TOKEN, ACCESS_KEY, ACESS_TOKEN) # Followback all your followers if you are not already following them bot.follow_followers() # Like 100 tweets from the provided query bot.like_tweets(search_query) bot.follow_from_tweets(search_query)
parser = argparse.ArgumentParser(description='Respond to Twitter mentions.', epilog='example: main.py -l "happy birthday" \ "hbd" -r "thanks HANDLE!"') parser.add_argument('-l', '--listen', nargs='+', default=['happy birthday'], help='phrase(s) to reply to (separate by space)') parser.add_argument('-r', '--reply', default='HANDLE thanks!', help='reply text (use HANDLE for user handle)') # instantiate TwitterBot outside of main since it's required for reply args = parser.parse_args() bot = TwitterBot(keys, args.listen, args.reply.replace('HANDLE', '@{}')) def reply(bot=bot): print(' Running...') bot.reply_to_mention() print(' Finished running at {}'.format(datetime.datetime.now())) def main(): print('Starting bot...') # start loop, run once every 2 minutes scheduler = BlockingScheduler() scheduler.add_job(reply, 'interval', minutes=2) scheduler.start()
def setUp(self): self.bot = TwitterBot(config_file='tests/config_test.json')
fetchers = [] for i in xrange(feeds_count): # TODO: abstract fetcher_args object fetchers.append( FeedFetcher(feed_url=feeds[i], data_dir=data_dir, cache_dir=cache_dir, cache_feed=cache_feed, verbose=args.verbose, no_cache=args.no_cache)) if args.verbose > 2: print(fetchers) if args.twitter: # TODO: pass in all args twitter_bot = TwitterBot(args.config_file, args.verbose) tweeted_file = open(cp.get('General', 'tweeted'), 'r+') tweeted = set(tweeted_file.read().split('\n')) if args.verbose > 2: print(tweeted) if args.database: # TODO: abstract db_args object host = cp.get('General', 'db_host') user = cp.get('General', 'db_user') cred = cp.get('General', 'db_cred') db = cp.get('General', 'db_name') db_saver = DBSaver(host, user, cred, db, args=args) try: while True:
import json from twitterbot import TwitterBot with open('app/config/secret.json') as arq: credentials = json.load(arq) login = credentials['login'] password = credentials['password'] bot = TwitterBot(login, password) bot.reuitar('o jogo')