How to send a direct message with Twython? - python

I know this is a beginner question, but can someone please provide some sample code of sending a Twitter direct message (just text) with Twython? I can't seems to find a lot of specific documentation over this (I know it's briefly covered in the official docs but they aren't super clear to me). Thank you!

Solution
twitter.send_direct_message(event = {"type": "message_create",
"message_create":{"target": {"recipient_id": ID goes here},
"message_data":
{"text": "Hello World!"}}})
Explanation
In short, you take the raw JSON data that you would send as a POST request to Twitter, and use it as a parameter in the twitter.send_direct_message() function. When using the JSON as a parameter in Python, we must interpret it as a dictionary. This can be done by setting the parent object as the dictionary key, and what follows as the dictionary value. So, in my case the JSON:
{"event" : {"type": "message_create",
"message_create":{"target": {"recipient_id": ID goes here},
"message_data":
{"text": "Hello World!"}}}}
becomes:
event = {"type": "message_create",
"message_create":{"target": {"recipient_id": ID goes here},
"message_data":
{"text": "Hello World!"}}}
More information about what JSON data to send to Twitter for specific direct message requests can be found here.

Related

How to get formatted text with entities?

I need some help with telethon:
I have text from telethon message. Example: 'some text message'
And i have an entity. Example: {"_": "MessageEntityBold", "offset": 5, "length": 4}
I need some method or tip to get formated text like this: '''some <b>text</b> message'''
The Message.text returns the text formatted using the current parse mode of the client. By default, this is Telegram's markdown, which means you would get some **text** message with the following code:
print(message.text)
Please note that since it currently relies on the client.parse_mode, you cannot use the .text property for messages returned by raw API since the results are not modified there. Instead, the message must be fetched with a friendly method or through events.

Gmail API: Python Email Dict appears to be Missing Keys

I'm experiencing a strange issue that seems to be inconsistent with google's gmail API:
If you look here, you can see that gmail's representation of an email has keys "snippet" and "id", among others. Here's some code that I use to generate the complete list of all my emails:
response = service.users().messages().list(userId='me').execute()
messageList = []
messageList.extend(response['messages'])
while 'nextPageToken' in response:
pagetoken = response['nextPageToken']
response = service.users().messages().list(userId='me', pageToken=pagetoken).execute()
messageList.extend(response['messages'])
for message in messageList:
if 'snippet' in message:
print(message['snippet'])
else:
print("FALSE")
The code works!... Except for the fact that I get output "FALSE" for every single one of the emails. 'snippet' doesn't exist! However, if I run the same code with "id" instead of snippet, I get a whole bunch of ids!
I decided to just print out the 'message' objects/dicts themselves, and each one only had an "id" and a "threadId", even though the API claims there should be more in the object... What gives?
Thanks for your help!
As #jedwards said in his comment, just because a message 'can' contain all of the fields specified in documentation, doesn't mean it will. 'list' provides the bare minimum amount of information for each message, because it provides a lot of messages and wants to be as lazy as possible. For individual messages that I want to know more about, I'd then use 'messages.get' with the id that I got from 'list'.
Running get for each email in your inbox seems very expensive, but to my knowledge there's no way to run a batch 'get' command.

Push a raw value to Firebase via REST API

I am trying to use the requests library in Python to push data (a raw value) to a firebase location.
Say, I have urladd (the url of the location with authentication token). At the location, I want to push a string, say International. Based on the answer here, I tried
data = {'.value': 'International'}
p = requests.post(urladd, data = sjson.dumps(data))
I get <Response [400]>. p.text gives me:
u'{\n "error" : "Invalid data; couldn\'t parse JSON object, array, or value. Perhaps you\'re using invalid characters in your key names."\n}\n'
It appears that they key .value is invalid. But that is what the answer linked above suggests. Any idea why this may not be working, or how I can do this through Python? There are no problems with connection or authentication because the following works. However, that pushes an object instead of a raw value.
data = {'name': 'International'}
p = requests.post(urladd, data = sjson.dumps(data))
Thanks for your help.
The answer you've linked is a special case for when you want to assign a priority to a value. In general, '.value' is an invalid name and will throw an error.
If you want to write just "International", you should write the stringified-JSON version of that data. I don't have a python example in front of me, but the curl command would be:
curl -X POST -d "\"International\"" https://...
Andrew's answer above works. In case someone else wants to know how to do this using the requests library in Python, I thought this would be helpful.
import simplejson as sjson
data = sjson.dumps("International")
p = requests.post(urladd, data = data)
For some reason I had thought that the data had to be in a dictionary format before it is converted to stringified JSON version. That is not the case, and a simple string can be used as an input to sjson.dumps().

Suds error when creating a issue for Jira

i'm getting the following error every time that i try to send an issue to Jira:
suds.WebFault: Server raised fault: 'org.xml.sax.SAXException:
Found character data inside an array element while deserializing'
I search on stackoverflow and the web for the answer and some people say that is suds 0.3 < fault. But i'm using the 0.4.1.1 version.
Here is my issue dict:
issue = {"assignee": "user_test",
"components": "17311",
"project": "TES",
"description" : "This is a test",
"priority" : "Major",
"summary" : "Just a test title",
"type":"Incident"
}
Class Jira made by me:
def create_issue(self,issue):
if(not isinstance(issue,dict)):
raise Exception("Issue must be a dict")
new_issue = self.jira.service.createIssue(in0 = self.auth,in1 = issue)
return new_issue["key"]
Using jira-python I was able to add components with like:
jira.create_issue(project={'key': project_id}, summary=ticket_summary,
description=ticket_description, issuetype={'name': ticket_issue_type},
components=[{'name': 'Application Slow'},], parent={'id': new_issue_key}, customfield_10101=termination_change_date,
)
I kept trying to send a component as "components={'name': 'Application Slow'}", but I was getting a "data was not an array" (or something similar). I took a look at the REST API and how some of their array examples were composed which is how I came to my example above.
https://developer.atlassian.com/display/JIRADEV/JIRA+REST+API+Example+-+Create+Issue#JIRARESTAPIExample-CreateIssue-Request
Labels
"customfield_10006": ["examplelabelnumber1", "examplelabelnumber2"]
Labels are arrays of strings
I know this is a bit off topic, but when I searched for my issue I found myself coming back here often so I hope this is a bit helpful for your case and to anyone else. The concept is the same as the components field will only accept an array of objects.
components is not right. It has to be an array of things because it is multivalued. Some hints at https://developer.atlassian.com/display/JIRADEV/Creating+a+JIRA+SOAP+Client or look at how the JIRA Python CLI does it
'components': [17311]

related to freebase library

I'm using freebase library to get the article. But it is not working. I'm using this example. http://tinyurl.com/6ynwrbk Can any one fix this error? thanks
import freebase
query = {
"id": "/en/jimi_hendrix",
"/common/topic/article": [{
"text": {
"maxlength": 400,
"chars": None
}
}]
}
result = freebase.mqlread(query)
print (result)
##################################
Edit : Code Updated
The error you are getting is MQL complaining that there is no such property "chars". It works in the queryeditor because you are using MQL Extensions, a feature that is not currently supported.
Freebase doesn't store topic descriptions along with the other data due to size issues, but you can use the new Text API to retrieve them by id:
https://www.googleapis.com/freebase/v1-sandbox/text/en/jimi_hendrix
The python library you are using does not support this new API, but you can find more details and documentation, including library support here:
http://wiki.freebase.com/wiki/ApiText
python has no null keyword, instead it has None which is an object that represents a null-like value.
Also, the request in the link you posted appears to be json. Python's None will be encoded as null in json.
To solve your first problem, switch null with None.
To solve your second problem (in the comments), try (in your import/feature list):
import logging
logging.basicConfig()
Or, you can try a variant of the solution found here.
It might work. I hope this helped.

Categories

Resources