I'm trying to convert logging data to JSON to show it in ChatBot.I tried logging.Formatter but data still isn't showing in chatbot it throws an error.
I tried userInput = logging.Formatter(user_input).
After this I tried userInput = logging.Formatter(user_input)
user = userInput.json() but it didn't work as well.
How can I convert logging data to json for chatbot. Where I'm committing mistake kindly correct it. Code is below
this is the error I'm getting.
An error has occurred: Invalid Lambda Response: Received error response from Lambda: Unhandled
If you just want to see the logging info in the chatbot, you can convert that object into string and return it to chatbot.
def response(message):
return {
"dialogAction":{
"type":"Close",
"fulfillmentState":"Fulfilled",
"message":{
"contentType":"PlainText",
"content":message
}
}
}
return response(str(logging_info_object))
Hope it helps.
Related
I have a bot that has been running for almost a year now reading discord messages in a server channel. It uses the following code to get new messages in json format:
r = requests.get(f'https://discord.com/api/v9/channels/{channelid}/messages?limit=1', headers=headers)
jsonn = json.loads(r.text)
for value in jsonn:
print(value)
current = str(value['embeds'])[1:500]
if current != last:
This same code now throws up the following error
"current = str(value['embeds'])[1:500]
TypeError: string indices must be integers"
I am not sure why it has stopped working. Can anyone please explain/help?
If anyone else gets this - it is because my authorization expired and I had to insert a new one into the header. :)
I am working on a rest api using flask. Currently the code for the client is as follows:
new_data = {'msg': message,
'rec':rec_id,
'snd':my_id}
requests.post("http://localhost:33/api/resources/messages/all", json = new_data)
I did print out new_data and it does print fine it does print out fine
{'msg': 'This is a message', 'rec': 1, 'snd': 0}
and the code in the rest api is:
#app.route('/api/resources/messages/all', methods=['GET', 'POST'])
def api_messages():
if request.method == "GET":
return jsonify(messages)
if request.method == "POST":
sentmsg = request.json
print (sentmsg)
changing
sentmsg = request.json
to
sentmsg = request.get_json()
did not change anything as it still results in the same error. Specifying the content type also did not result in any changes to the result.
However this code results in the error when attempting to post it.
TypeError: Object of type type is not JSON serializable
How can I change this code in order to make it so the json is passed to the rest api and can be printed out in json form.
The issue did not originate from the code shown in the initial post. The error originates at the start of the code where I declared two of the variables used here:
my_id = int
rec_id = int
Since these 2 variables did not have a value it was causing issues when it was called. As such it resulted in the error message "TypeError: Object of type type is not JSON serializable" (This error message itself gives a good indicator that one or more of the variables used were likely blank and held no value, thus making it unable to specify the data type in the message).
As such giving these variables an actual value caused the program to work fine. A second error that only become obvious after was that request.get_json needed to have brackets after get_json, making it request.get_json().
I'm not quite sure why this piece of code fails, please I'd be happy to hear your thoughts. I've used examples from boto3 and its works in general, but I'd get an AttributeError all of a sudden in some cases. Please explain what I am doing wrong because if a payload is None, I will get a JSON decoding error but not a None object.
Here is a simplified version of a code that causes the exception.
import boto3
import json
client = boto3.client('lambda', region_name='...')
res = client.invoke(
FunctionName='func',
InvocationType='RequestResponse',
Payload=json.dumps({'param': 123})
)
payload = json.loads(res["Payload"].read().decode('utf-8'))
for k in payload.keys():
print(f'{k} = {payload[k]}')
The error
----
[ERROR] AttributeError: 'NoneType' object has no attribute 'keys'
Traceback (most recent call last):
.....
Just replicated your issue in my environment by creating a lambda that doesn't return anything and calling it using boto3. The "null" object passes through the json loads without error but doesn't have any keys since it's not a dictionary.
def lambda_handler(event, context):
pass
I created my code just like yours and got the same error. Weirdly, I was able to get the json error by attempting to print out the streaming body with this line
print(res["Payload"].read().decode('utf-8'))
before loading it. I have no idea why this happens.
Edit: Looks like once you read from the StreamingBody object it's empty from then on. https://botocore.amazonaws.com/v1/documentation/api/latest/reference/response.html#botocore.response.StreamingBody. My recommendation is to read the data from the streaming body and check for "null" and process as normal.
I'm using this slice of code to try to remove the label "INBOX" from a message, but i'm getting error "no label to remove or specify"
message = service.users().messages().modify(userId='me', id=id, body='INBOX').execute();
I think your body is wrong the body is a json object probably something like this
msg_labels = {'removeLabelIds': ['INBOX'], 'addLabelIds': []}
message = service.users().messages().modify(userId=user_id, id=msg_id,
body=msg_labels).execute()
You might want to check the documented example my python is very basic messages.modify python
I'm writing an app to post json to Django, but get a 500 error in terminal like
[27/Jan/2015 20:50:38] "POST /datasave/ds/ HTTP/1.1" 500 10414
This is my jQuery code:
$(function() {
$('#upload').click(function() {
var json_obj = {
username: $('#username').val(),
password: $('#password').val(),
game_id1: '123',
csrfmiddlewaretoken: '{{ csrf_token}}'
};
$.post("http://192.168.0.109:8000/datasave/ds/", JSON.stringify(json_obj),
function(data) {
alert("OK");
},
"json");
})
})
And Django views code:
#csrf_exempt
def ds(request):
dicty = {}
if request.is_ajax:
if request.method == 'POST':
req = json.loads(request.body.decode("utf-8"))
obj, created =
Gamer.objects.update_or_create(
username=req.get(u'username', None),
password=req.get(u'password', None),
game_id1=req.get(u'game_id1', None))
print obj, created
dicty['username'] = req.get(u'username', None)
dicty['password'] = req.get(u'password', None)
dicty['create_at'] = str(timezone.now())
return JsonResponse(dicty)
As you are getting a 500 Internal server error one could assume that there is an issue in your view handler code. It's hard to say what's causing it really, so you should try to figure why it's happening. From looking at your code I can see two things that might cause this error.
First you are using dict as a variable name, which is probably a bad idea since dict is a built-in type in python.
The other possible cause could be the way your are accessing the req dict. You are accessing the keys username, password and game_id1. If any of these should be missing in the dict it will throw a KeyError exception. I like to access dicts using req.get('username', None) instead (replace None with another default value if you prefer. Another way to tackle that issue would be try/catch exception handling.
Also, depending on your Gamer model, trying to create a using an existing username (assuming you have unique=True) would probably throw an exception as well, so you should handle that as well (I think get_or_create could be handy here).
Generally when dealing with problems of this kind, use the inspector in your browser. It lets you see all the data sent and received during the request, which means (if you're running django in DEBUG mode) you'll also get to see the default stack trace page in the inspector. It should hold some valuable indication to what's causing the issue. Another option would be to write a small middleware or enable extended error logging to log errors to strout/stderr.