Tweepy follow Twitter users from text file using user_id (Python script) - python

I am trying to follow user_ids from a text file with 27 user_ids - one per line, e.g. :
217275660
234874181
27213931
230766319
83695362
234154065
68385750
I have some code that seems to work except it says user_id isn't defined (see pasted error at the bottom)... but user_id should be the correct variable in Tweepy... with or without [,follow] afterwards. My code is as follows:
# Script to follow Twitter users from text file containing user IDs (one per line)
# Header stuff I've just thrown in from another script to authenticate
import json
import time
import tweepy
import pprint
from tweepy.parsers import RawParser
from auth import TwitterAuth
from datetime import datetime
auth = tweepy.OAuthHandler(TwitterAuth.consumer_key, TwitterAuth.consumer_secret)
auth.set_access_token(TwitterAuth.access_token, TwitterAuth.access_token_secret)
rawParser = RawParser()
api = tweepy.API(auth_handler = auth, parser = rawParser)
# Open to_follow.txt
to_follow = [line.strip() for line in open('to_follow.txt')]
print to_follow
# Follow everyone from list?!
for user_id in to_follow:
try:
api.create_friendship(user_id)
except tweepy.TweepError as e:
print e
continue
print "Done."
The error is:
$ python follow.py
['217275660', '234874181', '27213931', '230766319', '83695362', '234154065', '68385750', '94981006', '215003131', '30921943', '234526708', '229259895', '88973663', '108144701', '233419650', '70622223', '95445695', '21756719', '229243314', '18162009', '224705840', '49731754', '19352387', '80815034', '17493612', '23825654', '102493081']
Traceback (most recent call last):
File "follow.py", line 30, in <module>
api.create_friendship(user_id)
NameError: name 'user_id' is not defined

Indeed user_id isn't defined anywhere in your code.
I think you meant to do:
for user_id in to_follow:
The user_id's are in the list
And on a side note - the following code is better and more orthodox:
with open('to_follow.txt') as f:
for line in f:
user_id = line.strip()
api.create_friendship(user_id)

Related

Insert or update to a salesforce by python

I want to insert or update to a salesforce record.
by python but I get the following error.
The item of "SeqNo__c" is "202102-123" from that I specify the id of the record I want to change.
it seems that it cannot find it at SeqNo__c.
If anyone knows, please let me know.
This code
from simple_salesforce import Salesforce
from datetime import datetime
import os
import json
import gzip
from pytz import timezone
import requests
#strDate = datetime.now().strftime("%Y%m%d")
#strTime = datetime.now().strftime("%H%M%S")
SALESFORCE_USERNAME = '123#gmail.com'
PASSWORD = '12345'
SECURITY_TOKEN = '12345'
# Authentication settings
sf = Salesforce(username=SALESFORCE_USERNAME,
password=PASSWORD,
security_token=SECURITY_TOKEN)
#Try bulk but also error
#data = [{'SeqNo__c': '202102-123', 'NewNO__c': '1'}]
#sf.bulk.Contact.update(data)
sf.Contact.upsert('SeqNo__c/202102-123',{'NewNO__c': '1'})
error code
Traceback (most recent call last):
File "c:\Users\test\Documents\salesforce\sf_check.py", line 27, in <module>
sf.Contact.upsert('SeqNo__c/202102-123',{'NewNO__c': '1'})
File "C:\Users\test\AppData\Local\Programs\Python\Python39\lib\site-packages\simple_salesforce\api.py", line 694, in upsert
result = self._call_salesforce(
File "C:\Users\test\AppData\Local\Programs\Python\Python39\lib\site-packages\simple_salesforce\api.py", line 800, in _call_salesforce
exception_handler(result, self.name)
File "C:\Users\test\AppData\Local\Programs\Python\Python39\lib\site-packages\simple_salesforce\util.py", line 68, in exception_handler
raise exc_cls(result.url, result.status_code, name, response_content)
simple_salesforce.exceptions.SalesforceResourceNotFound: Resource Contact Not Found. Response content: [{'errorCode': 'NOT_FOUND', 'message': 'Provided external ID field does not exist or is not accessible: SeqNo__c'}]
PS C:\Users\test\Documents\salesforce>
Is the Contact.SeqNo__c field marked as external id? There's a checkbox in field definition that must be ticked. And your user needs to have a profile permission to at least see the field

How can I take a single column from a SQL query and add it to a list in Python

I have a SQL query that will search a database and return a single row containing at least 3 different columns as follows:
SELECT
`epg_num` AS `epgNum`,
`service_key` AS `serviceKey`,
`service_name` AS `channelName`
FROM `ssr_services`
WHERE `epg_num` = %(channelValue)s
I only require the Service Key to added to a list in my code.
The above SQL query cannot be amended as it is used by other things and I would prefer not to write a new query just for this one function. The above query is also a function in another module that I am calling to try and extract the Service Key.
The user will specify the epg_num when running the code. Which will then bring back a row in SQL showing the epg_num, service key and service name
Imports:
import sys
import os
import MySQLdb
from subprocess import check_output, CalledProcessError
from collections import OrderedDict
from UPnP.core.proxy import ServerProxy
from Data_Types import PlannerExportEvent, PlannerExportResponse, UpnpError, Result, Channel, Event, Shelf
from Database_Connection import FetchAll, FetchOne
from Decorators import ResetRetry, Suppress
from Logs import Logging
from Utilities import GetRecycID, GetRackID, Wait
The code I have at the moment is as follows:
if epgNumsList:
serviceKeysList = self.GetMultiChannelInfo(epgNumsList=epgNumsList)
print(serviceKeysList)
whereString = "(epg_num IN ({epgNumsList}) AND epg_num LIKE '___')".format(epgNumsList=','.join(epgNumsList))
Which uses the following:
def GetMultiChannelInfo(self, epgNumsList=None):
serviceKeys = []
for epgNum in epgNumsList:
retObj = self.GetChannelInfo(epgNum=epgNum)
result = retObj.Result()
if result:
channelObj = retObj.Data()
result = channelObj.serviceKey
serviceKeys.append(result)
print(result)
else:
print('Channel not found')
print(serviceKeys)
return Result(serviceKeys)
I am seeing the following error:
Traceback (most recent call last):
File "C:\Users\MHE36\workspace\Scripts\SkyPlus__UPnP_Set_Recordings.py", line 42, in <module>
upnp.BackgroundRecordings(recordings, epgNumsList, serviceKeysList, duration)
File "C:\Users\MHE36\workspace\Libraries\SuperPlanner.py", line 1154, in BackgroundRecordings
print(serviceKeysList)
File "C:\Users\MHE36\workspace\Libraries\Data_Types.py", line 32, in __repr__
return 'Result (Result: {result}, Data: {data}, NumFailures: {numFailures})'.format(result=self.result, numFailures=self.numFailures)
KeyError: 'data'
I think the trace back related to this bit of code from another module:
def __repr__(self):
return 'Result (Result: {result}, Data: {data}, NumFailures: {numFailures})'.format(result=self.result, numFailures=self.numFailures)
Hopefully this gives enough detail but happy to provide more if needed.
Thanks in advance.
How are you executing that query? with pyodbc?
then you can actually turn that particular row in to a dictionary
columns = [column[0] for column in cursor.description]
list_of_dict =[]
for dict in cursor.fetchall():
list_of_dict.append(dict(zip(columns, dict)))
print that list_of_dict and you'll understand everything.
Note : you should not execute other queries before performing that code block because cursor will be refreshed.
What I suggest is you is that you access that list and return what you want at the time you are executing that query for some reason.

Getting KeyError when parsing JSON containing three layers of keys, using Python

I'm building a Python program to parse some calls to a social media API into CSV and I'm running into an issue with a key that has two keys above it in the hierarchy. I get this error when I run the code with PyDev in Eclipse.
Traceback (most recent call last):
line 413, in <module>
main()
line 390, in main
postAgeDemos(monitorID)
line 171, in postAgeDemos
age0To17 = str(i["ageCount"]["sortedAgeCounts"]["ZERO_TO_SEVENTEEN"])
KeyError: 'ZERO_TO_SEVENTEEN'
Here's the section of the code I'm using for it. I have a few other functions built already that work with two layers of keys.
import urllib.request
import json
def postAgeDemos(monitorID):
print("Enter the date you'd like the data to start on")
startDate = input('The date must be in the format YYYY-MM-DD. ')
print("Enter the date you'd like the data to end on")
endDate = input('The date must be in the format YYYY-MM-DD. ')
dates = "&start="+startDate+"&end="+endDate
urlStart = getURL()
authToken = getAuthToken()
endpoint = "/monitor/demographics/age?id=";
urlData = urlStart+endpoint+monitorID+authToken+dates
webURL = urllib.request.urlopen(urlData)
fPath = getFilePath()+"AgeDemographics"+startDate+"&"+endDate+".csv"
print("Connecting...")
if (webURL.getcode() == 200):
print("Connected to "+urlData)
print("This query returns information in a CSV file.")
csvFile = open(fPath, "w+")
csvFile.write("postDate,totalPosts,totalPostsWithIdentifiableAge,0-17,18-24,25-34,35+\n")
data = webURL.read().decode('utf8')
theJSON = json.loads(data)
for i in theJSON["ageCounts"]:
postDate = i["startDate"]
totalDocs = str(i["numberOfDocuments"])
totalAged = str(i["ageCount"]["totalAgeCount"])
age0To17 = str(i["ageCount"]["sortedAgeCounts"]["ZERO_TO_SEVENTEEN"])
age18To24 = str(i["ageCount"]["sortedAgeCounts"]["EIGHTEEN_TO_TWENTYFOUR"])
age25To34 = str(i["ageCount"]["sortedAgeCounts"]["TWENTYFIVE_TO_THIRTYFOUR"])
age35Over = str(i["ageCount"]["sortedAgeCounts"]["THIRTYFIVE_AND_OVER"])
csvFile.write(postDate+","+totalDocs+","+totalAged+","+age0To17+","+age18To24+","+age25To34+","+age35Over+"\n")
print("File printed to "+fPath)
csvFile.close()
else:
print("Server Error, No Data" + str(webURL.getcode()))
Here's a sample of the JSON I'm trying to parse.
{"ageCounts":[{"startDate":"2016-01-01T00:00:00","endDate":"2016-01-02T00:00:00","numberOfDocuments":520813,"ageCount":{"sortedAgeCounts":{"ZERO_TO_SEVENTEEN":3245,"EIGHTEEN_TO_TWENTYFOUR":4289,"TWENTYFIVE_TO_THIRTYFOUR":2318,"THIRTYFIVE_AND_OVER":70249},"totalAgeCount":80101}},{"startDate":"2016-01-02T00:00:00","endDate":"2016-01-03T00:00:00","numberOfDocuments":633709,"ageCount":{"sortedAgeCounts":{"ZERO_TO_SEVENTEEN":3560,"EIGHTEEN_TO_TWENTYFOUR":1702,"TWENTYFIVE_TO_THIRTYFOUR":2786,"THIRTYFIVE_AND_OVER":119657},"totalAgeCount":127705}}],"status":"success"}
Here it is again with line breaks so it's a little easier to read.
{"ageCounts":[{"startDate":"2016-01-01T00:00:00","endDate":"2016-01-02T00:00:00","numberOfDocuments":520813,"ageCount":
{"sortedAgeCounts":{"ZERO_TO_SEVENTEEN":3245,"EIGHTEEN_TO_TWENTYFOUR":4289,"TWENTYFIVE_TO_THIRTYFOUR":2318,"THIRTYFIVE_AND_OVER":70249},"totalAgeCount":80101}},
{"startDate":"2016-01-02T00:00:00","endDate":"2016-01-03T00:00:00","numberOfDocuments":633709,"ageCount":
{"sortedAgeCounts":{"ZERO_TO_SEVENTEEN":3560,"EIGHTEEN_TO_TWENTYFOUR":1702,"TWENTYFIVE_TO_THIRTYFOUR":2786,"THIRTYFIVE_AND_OVER":119657},"totalAgeCount":127705}}],"status":"success"}
I've tried removing the ["sortedAgeCounts"] from in the middle of
age0To17 = str(i["ageCount"]["sortedAgeCounts"]["ZERO_TO_SEVENTEEN"])
but I still get the same error. I've remove the 0-17 section to test the other age ranges and I get the same error for them as well. I tried removing all the underscores from the JSON and then using keys without the underscores.
I've also tried moving the str() to convert to string from the call to where the output is printed but the error persists.
Any ideas? Is this section not actually a JSON key, maybe a problem with the all caps or am I just doing something dumb? Any other code improvements are welcome as well but I'm stuck on this one.
Let me know if you need to see anything else. Thanks in advance for your help.
Edited(This works):
JSON=json.loads(s)
for i in JSON:
print str(JSON[i][0]["ageCount"]["sortedAgeCounts"]["ZERO_TO_SEVENTEEN"])
s is a string which contains the your JSON.

SUDS client.service. issue

I am utterly lost at what should be an easy task.
I am trying to use Python with SUDS to grab a WSDL URL, create client objects, modify some information, and then post back up the WSDL (Or where ever it tell me to post it).
I get the following error message:
Traceback (most recent call last):
File "./test.py", line 47, in <module>
email_sent = client.service.sendEmail(From, SenderContext, Email)
NameError: name 'client' is not defined
If I remove the "Try:" section in the code and insert come print code to print the objects, everything works just fine. It does grab the information and do the changes I want.
What I don't understand is that the client object is created and I am trying to post the information back up, but can't. Any one have any experience with XML and Python?
import sys
import logging
import traceback as tb
import suds.metrics as metrics
import unittest
from suds import null, WebFault
from suds.client import Client
def sendTestMail():
url = 'wsdl url at my company'
client = Client(url)
SenderContext = client.factory.create('senderContext')
SenderContext.registeredSenderId = 'Endurance'
SenderContext.mailType = 'TRANSACTIONAL_OTHER'
SenderContext.subSenderId = 12345
From = client.factory.create('emailAddressBean')
From.address = 'me#somecompany.com'
From.valid = 'TRUE'
Email = client.factory.create('email')
Email.recipients = 'me#somecompany.com'
Email.ccRecipients = ''
Email.bccRecipients = ''
Email.agencyId = ''
Email.content = 'This is a test of sending'
Email.contentType = 'text/plain'
Email.description = ''
#Email.from = From
Email.fromName = 'An Employee'
Email.subject = 'This is a test'
Email.mrrId = ''
Email.templateId = ''
try:
email_sent = client.service.sendEmail(From, SenderContext, Email)
except WebFault, e:
print e
if __name__ == '__main__':
errors = 0
sendTestMail()
print '\nFinished: errors=%d' % errors
You define client in the sendTestMail() class, but then use a lower-level indentation in your try/except statement. Therefore, client is not within scope at this point. Either indent your try/except block to be within the sendTestMail() scope or declare client globally.

Updating a Spreadsheet in Google Docs

I have a python script that takes a generated CSV and uploads it to Google Docs. It can upload it just fine, put I cannot seem to get it to replace the data, it returns an error I cannot find reference to.
Le Code:
import gdata.auth
import gdata.docs
import gdata.docs.service
import gdata.docs.data
import gdata.docs.client
email = 'admin#domain.com'
CONSUMER_KEY='domain.com'
CONSUMER_SECRET='blah54545blah'
ms_client = gdata.docs.client.DocsClient('Domain_Doc_Upload')
ms_client.auth_token = gdata.gauth.TwoLeggedOAuthHmacToken(CONSUMER_KEY, CONSUMER_SECRET, email)
url = 'http://docs.google.com/feeds/documents/private/full/sd01blahgarbage'
ms = gdata.data.MediaSource(file_path="C:\\people.csv", content_type='text/csv')
csv_entry2 = ms_client.Update(url, ms)
It returns:
Traceback (most recent call last):
File "so_test.py", line 19, in <module>
csv_entry2 = ms_client.Update(ms, url)
File "build\bdist.win-amd64\egg\gdata\client.py", line 717, in update
AttributeError: 'MediaSource' object has no attribute 'to_string'
I cannot find anything about the 'to_string' attribute, so I am lost on the trace. ANy help, much appreciated.
I took a look at the docs and it looks like the Update method takes (entry, ms) where entry needs to be a gdata.docs.data.DocsEntry object. You should be able to get the DocsEntry object by getting a feed from your client.
feed = client.GetDocList()

Categories

Resources