Is there a way to index a tweet with Tweepy? - python

I'm trying to script a Twitter bot that will respond to mentions that have equations in them. First, I got the mentions to work (it would respond to anyone who mentions it). Then, I tried to implement the math function which uses regex (I had already created this, it was just a means of integrating it into the main bot program).
The Code for Mentions:
import mathbotcreds as mtc
import logging
import re
import tweepy
from time import sleep as wait
auth = tweepy.OAuthHandler(mtc.CONSUMER_KEY, mtc.CONSUMER_SECRET)
auth.set_access_token(mtc.ACCESS_TOKEN, mtc.ACCESS_SECRET)
api = tweepy.API(auth, wait_on_rate_limit=True,
wait_on_rate_limit_notify=True,
retry_count=2)
try:
api.verify_credentials()
print("Authentication Successful!")
except:
print("Error during authentication! :(")
mentions = api.mentions_timeline()
pattern = r'([0-9]+.*[-+*/%].*[0-9]+)+'
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger()
def check_mentions(api, since_id):
logger.info("Collecting mentions... ")
new_since_id = since_id
for tweet in tweepy.Cursor(api.mentions_timeline, since_id=since_id).items():
new_since_id = max(tweet.id, new_since_id)
if tweet.in_reply_to_status_id is not None:
continue
api.update_status(
status=f"Hello! \n\nIt worked! \nYay! ^-^ \n\n (You said: \"{tweet.text}\".)",
in_reply_to_status_id=tweet.id)
return new_since_id
def main():
since_id = 1
while True:
since_id = check_mentions(api, since_id)
logger.info("Waiting... ")
wait(15)
if __name__ == "__main__":
logger.info("Running script... ")
wait(1)
main()
# for m in mentions:
# api.update_status(f"#{m.user.screen_name} Hello! \nYou said: \n{m.text}", m.id)
# wait(15)
The Code for Mentions and Equations Functions:
import mathbotcreds as mtc
import logging
import re
import tweepy
from time import sleep as wait
auth = tweepy.OAuthHandler(mtc.CONSUMER_KEY, mtc.CONSUMER_SECRET)
auth.set_access_token(mtc.ACCESS_TOKEN, mtc.ACCESS_SECRET)
api = tweepy.API(auth, wait_on_rate_limit=True,
wait_on_rate_limit_notify=True,
retry_count=2)
try:
api.verify_credentials()
print("Authentication Successful!")
except:
print("Error during authentication! :(")
mentions = api.mentions_timeline()
pattern = r'([0-9]+.*[-+*/%].*[0-9]+)+'
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger()
def check_mentions(api, since_id):
logger.info("Collecting mentions... ")
new_since_id = since_id
for tweet in tweepy.Cursor(api.mentions_timeline, since_id=since_id).items():
match = re.search(pattern, tweet.text)
equation = tweet.text[match.start():match.end()]
new_since_id = max(tweet.id, new_since_id)
if tweet.in_reply_to_status_id is not None:
continue
if match:
ans = eval(tweet.text[match.start():match.end()])
api.update_status(
status=f"The answer to {str(equation)} is {ans}. ",
in_reply_to_status_id=tweet.id)
elif not match:
api.update_status(
status=f"Hello! \n\nIt worked! \nYay! ^-^ \n\n (You said: \"{tweet.text}\".)",
in_reply_to_status_id=tweet.id)
return new_since_id
def main():
since_id = 1
while True:
since_id = check_mentions(api, since_id)
logger.info("Waiting... ")
wait(15)
if __name__ == "__main__":
logger.info("Running script... ")
wait(1)
main()
# for m in mentions:
# api.update_status(f"#{m.user.screen_name} Hello! \nYou said: \n{m.text}", m.id)
# wait(15)
When I run this, I get an error stating, AttributeError: 'NoneType' object has no attribute 'start' on the eval() function (equation = tweet.text[match.start():match.end()]). I have researched this and how to index tweet text (with Tweepy). I'm confused as to why I get a NoneType error if I have a function directly above the eval() function. Shouldn't this catch that? Why does this happen?
Thanks!

re.search returns a NoneType when it doesn't find a match. You should check the return value before using it, like this:
match = re.search(pattern, tweet.text)
if match:
equation = tweet.text[match.start():match.end()]

Related

Python Speech Recognition not working when the file is converted to exe with pyinstaller

I created a Voice Assistant using speech recognition and GTTS modules in Python. The code works perfectly fine when run from script. But when I converted it using pyinstaller --onefile Speak.py(The name of the file) it stopped working. It is using my microphone but its not responding to anything. Suppose if I say hey google which is the wake up keyword it simply doesnt respond. I tried after a while but of no use. Can anyone please help me???
Code:
"from gtts import gTTS
import speech_recognition as sr
import os
import playsound
from datetime import datetime
import webbrowser
keeprunning = True
WAKING = "HEY GOOGLE"
def chec(cond, tex):
if cond in tex:
return True
else:
return False
def speak(text):
speaker = gTTS(text = text, lang = "en")
speaker.save("Voice.mp3")
playsound.playsound("voice.mp3")
os.remove("Voice.mp3")
def cleanify(text, wtremove, wtremove2=""):
try:
text = text.replace(wtremove)
except:
if not wtremove2 == "":
text = text.replace(wtremove2, "")
return text
#Main controlling part here(Oof!)
def Control(comnd):
if chec("SEARCH", comnd) or chec("GOOGLE", comnd):
comnd = cleanify(comnd, "SEARCH", "GOOGLE")
webbrowser.open(f"https://google.com/search?q={comnd.lower()}")
elif chec("WHO ARE YOU", comnd):
speak("I am your virtual assistant, google")
keepcontrol()
elif chec("TIME", comnd):
t = datetime.now()
t = time.strptime(t.strftime("%H:%S"), "%H:%M")
tt = time.strftime( "%I:%M %p", t )
speak(f"The current time is {tt}")
elif chec("NOTE", comnd) or chec("REMEMBER", comnd) or chec("JOT", comnd):
try:
text = comnd.replace("NOTE")
except:
try:
text = text.replace("REMEMBER")
except:
text = text.replace("JOT")
try:
with open("This_File_Name_Is_Very_Big_Because_I_dont_Want_to_overwrite_anyother_files_so_forgive_me_plz.txt", "rt") as file:
previous = file.read()
except:
with open("This_File_Name_Is_Very_Big_Because_I_dont_want_to_overwrite_any_other_files_so_forgive_me_plz.txt", "wt") as file:
ttw = f"""
•{text.lower()}
"""
file.write(previous + ttw)
previous = ""
with open("Notes.txt", "wt") as file:
ttw = previous + " •" + text
file.write(ttw)
speak("Got it! I noted it down")
elif chec("OPEN", comnd):
web = cleanify(comnd, "OPEN")
bruh = cleanify(web, ".com")
speak(f"Opening {bruh}")
print(comnd)
web = cleanify(comnd, "OPEN")
if web == "":
web = listen()
else:
if "https://" in web:
webbrowser.open(web.lower())
else:
web = "https://" + web
webbrowser.open(web.lower())
keepcontrol()
#Main controlling part ends
def listen():
r = sr.Recognizer()
with sr.Microphone() as source:
listen = r.listen(source)
try:
text = r.recognize_google(listen)
return text.upper()
except Exception as e:
if not e == "":
return ""
keepcontrol()
else:
speak("Sorry we couldnt catch that, please try again")
keepcontrol()
def keepcontrol():
while keeprunning:
text = listen()
if not text == None:
if text.count(WAKING) == 1:
speak("I am listening..")
text = listen()
if not text == None and not text == "":
Control(text)
else:
speak("Sorry i did not get that. Try again in a few seconds")
keepcontrol()
elif chec("QUIT", text):
exit()
elif chec("", text):
keepcontrol()
else:
speak("Sorry we didnt get that right. Please try again.")
speak("I am booting up...")
keepcontrol()
"
When you have converted it into exe,I think you have forgot to put files that you have used to build the assistant in the folder.
When your exe get converted, just simply copy those files(the files you have used) in the same folder in which you have kept your exe.
Hope it will work.

TabError: inconsistent use of tabs and spaces in indentation (except: ^)

I have a code like as below.. but there is something wrong in my main code.. Anyone can help me to spot the problem... I am literally stuck at this indentation error... It says there is indentation error occurered at except: in the main function...
import tweepy
from datetime import datetime,timedelta
import csv
def get_all_tweets(screen_name):
consumer_key = *
consumer_secret = *
access_key = *
access_secret = *
#authorize twitter, initialize tweepy
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_key, access_secret)
api = tweepy.API(auth, wait_on_rate_limit_notify=True)
noRT = []
search_terms = 'superbowl ', 'super bowl ', '#superbowl'
for page in tweepy.Cursor(api.user_timeline,
screen_name = screen_name,
tweet_mode="extended",
wait_on_rate_limit=True,
include_retweets=False,
count=100).pages(20):
for status in page:
noRT.append([status.id_str, status.created_at, status.full_text.encode("utf-8")])
# do your process on status
with open('{}_tweets.csv'.format(screen_name), 'w') as f:
writer = csv.writer(f)
writer.writerow(["id","created_at","text"])
writer.writerows(noRT)
print('{}_tweets.csv was successfully created.'.format(screen_name))
pass
if __name__ == '__main__':
usernames = ["GregoryBlakley","Minihova","TheAMRCentre","throse_gd","CDCgov","TheAMRCentre","GuyFema","EndGameWW3","ABC","Childishnegrit0","WorldPeace24_7","byetofi","mumabear13"]
for x in usernames:
try:
get_all_tweets(x)
except:
print "%s does not exist" % (twitter_id)
pass
What's wrong with this code?
if __name__ == '__main__':
usernames = ["GregoryBlakley","Minihova","TheAMRCentre","throse_gd","CDCgov","TheAMRCentre","GuyFema","EndGameWW3","ABC","Childishnegrit0","WorldPeace24_7","byetofi","mumabear13"]
for x in usernames:
try:
get_all_tweets(x)
except:
print "%s does not exist" % (twitter_id)
pass
You're mixing tabs and spaces inside your for loops, e.g.:
Python 3 disallows mixing the use of tabs and spaces for indentation.

how to check if cpanel can login successfully with python2.7?

i need a script to make it like a cpanel checker, with more than 1 url and the url is stored in a txt file.
usage : python script.py list.txt
format in file list.txt : https://demo.cpanel.net:2083|democom|DemoCoA5620
this is my code but it doesn't work, can someone help me?
Thanks.
import requests, sys
from multiprocessing.dummy import Pool as ThreadPool
try:
with open(sys.argv[1], 'r') as f:
list_data = [line.strip() for line in f if line.strip()]
except IOError:
pass
def cpanel(url):
try:
data = {'user':'democom', 'pass':'DemoCoA5620'}
r = requests.post(url, data=data)
if r.status_code==200:
print "login success"
else:
print "login failed"
except:
pass
def chekers(url):
try:
cpanel(url)
except:
pass
def Main():
try:
start = timer()
pp = ThreadPool(25)
pr = pp.map(chekers, list_data)
print('Time: ' + str(timer() - start) + ' seconds')
except:
pass
if __name__ == '__main__':
Main()
I fixed your code in a way that it will return an actual array containing a boolean array indicating the success of the cpanel function.
from __future__ import print_function
import requests
from multiprocessing.pool import ThreadPool
try:
list_data = ["https://demo.cpanel.net:2083|democom|DemoCoA5620",
"https://demo.cpanel.net:2083|UserDoesNotExist|WRONGPASSWORD",
]
except IOError:
pass
def cpanel(url):
try:
# try to split that url to get username / password
try:
url, username, password = url.split('|')
except Exception as e:
print("Url {} seems to have wrong format. Concrete error: {}".format(url, e))
return False
# build the correct url
url += '/login/?login_only=1'
# build post parameters
params = {'user': username,
'pass': password}
# make request
r = requests.post(url, params)
if r.status_code==200:
print("login for user {} success".format(username))
return True
else:
print("login for user {} failed due to Status Code {} and message \"{}\"".format(username, r.status_code, r.reason))
return False
except Exception as e:
print("Error occured for url {} ".format(e))
return False
def chekers(url):
return cpanel(url)
def Main():
try:
# start = timer()
pp = ThreadPool(1)
pr = pp.map(chekers, list_data)
print(pr)
# print('Time: ' + str(timer() - start) + ' seconds')
except:
pass
if __name__ == '__main__':
Main()
Output:
login for user democom success
login for user UserDoesNotExist failed due to Status Code 401 and message "Access Denied"
[True, False]
Be aware that I replaced your file read operation by some fixed urls.
Since you use request.post I guess you actually want to POST something to that urls. Your code does not do that. If you just want to send a request, use the requests.get method.
See the official documentation for the requests packet: https://2.python-requests.org/en/master/user/quickstart/#make-a-request for more details.
Also note that
"but it doesn't work"
is NOT a question.

Tweepy stream ignoring some twitter accounts

I am working on the finishing touches on my tweepy twitter bot for my LED. I have been testing it with different accounts, and something weird is going on. With my personal account I tweet and it does nothing. My filter doesn't detect the hashtags and it just ignores everything. My friends have been able to use it, so I decided to log onto a separate twitter account. I can tweet there and my bot sees it and recognizes it.
I really have no clue what could cause this. Is it a problem with my bot, or is it with the accounts?
import tweepy
import requests
import json
consumer_key = 'nein'
consumer_secret = 'das'
access_token = 'ist'
access_token_secret = 'böse'
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth, wait_on_rate_limit=True)
user = api.me()
print(user.name)
counter = 0
class LEDStreamListener(tweepy.StreamListener):
def on_data(self, raw_data):
with open("tweets.json", "w") as write_file:
write_file.write(raw_data)
data = json.loads(raw_data)
variable_checker(data)
def on_error(self, status_code):
if status_code == 420:
print('Stream disconnect, because of rate limit error')
return False
else:
print('Unknown Error ' + status_code)
return False
def retweet_tweet(tweet_id):
api.retweet(tweet_id)
api.create_favorite(tweet_id)
def tag_checker(tag_list):
for i in range(0, len(tag_list)):
iterated_tag = tag_list[i]['text']
if iterated_tag == 'HUNTER_LED_ON':
return iterated_tag
elif iterated_tag == 'HUNTER_LED_OFF':
return iterated_tag
elif iterated_tag == 'led_test':
return iterated_tag
return ' '
def variable_checker(json_file):
if 'delete' in json_file:
# If the tweet was deleted do nothing
print('Delete')
else:
usr = json_file['user']['screen_name']
tweet_id = json_file['id_str']
print(tweet_id)
text = json_file['text']
tag_list = json_file['entities']['hashtags']
tag = tag_checker(tag_list)
data_check(usr, tweet_id, tag, text)
def data_check(twitter_user, tweet, tag, text):
if tag == 'HUNTER_LED_OFF' and not text.startswith('RT'):
requests.get('http://192.168.1.175/off')
retweet_tweet(tweet)
api.update_status('I turned the led off for you', tweet)
print('off')
return
elif tag == 'HUNTER_LED_ON' and not text.startswith('RT'):
requests.get('http://192.168.1.175/on')
retweet_tweet(tweet)
api.update_status('I turned the led on for you', tweet)
print('on')
return
elif tag == 'led_test' and not text.startswith('RT'):
retweet_tweet(tweet)
reply = 'Nice test bro *highfives* keep up the good work'
api.update_status('#%s %s' % (twitter_user, reply), in_reply_to_status_id=tweet)
print('tested')
return
elif twitter_user == 'realDonaldTrump':
api.create_favorite(tweet)
requests.get('http://192.168.1.175/trump')
print('Make America Great Again!')
return
else:
return
ledStreamListener = LEDStreamListener()
ledStream = tweepy.Stream(auth=api.auth, listener=ledStreamListener)
ledStream.filter(track=['#HUNTER_LED_OFF', '#HUNTER_LED_ON', '#led_test'])
It could have something to do with Twitter only making available about 1% of tweets for streaming to most users. Twitter does offer a "Firehose" account that gives you everything but it's rather expensive.
You could poll your users timeline every few seconds rather than using the streaming API.
new_tweets = api.user_timeline(user_id = user_id,count= 1)

how to stream tweets for a particular time period in the past

I am using the following python code to get tweets for a particular topic
import sys
from tweepy import *
import time
import csv
CONSUMER_KEY = ''
CONSUMER_SECRET = ''
OAUTH_TOKEN = ''
OAUTH_TOKEN_SECRET = ''
class listener(StreamListener):
def on_data(self,data):
try:
saveFile=open('tweetDB2.csv','a')
saveFile.write(data)
saveFile.write('\n')
saveFile.close()
return True
except BaseException as e:
print('failed ondata,',str(e))
time.sleep(60)
def on_error(self,status):
print(status)
auth = OAuthHandler(CONSUMER_KEY,CONSUMER_SECRET)
auth.set_access_token(OAUTH_TOKEN,OAUTH_TOKEN_SECRET)
twitterStream = Stream(auth,listener())
twitterStream.filter(track=["IPL"])
How do I modify the code to get tweets for the same topic but for a different time period (say 2nd week of April,2015)? I went through the API parameters(https://dev.twitter.com/streaming/overview/request-parameters).But I could not find anything with respect to time period. Thanks!

Categories

Resources