Youtube Python API LiveChatMessages insert ERROR_UNSPECIFIED - python

I'm working on writing a python script that utilizes the Youtube Live API. I can read messages using the liveChatMessages().list() method, but am getting a strange error about an invalid argument when I attempt to create a message with liveChatMessages().insert().
The below is the source code responsible for sending messages:
def send_message(self, message):
body = {
'snippet': {
'liveChatId': self.stream_id,
'type': 'textMessageEvent',
'textMessageDetails': {
'messageText': message
}
}
}
self.youtube.liveChatMessages().insert(part='snippet', body=body).execute()
The following is the errror that I'm getting
googleapiclient.errors.HttpError: <HttpError 400 when requesting https://youtube.googleapis.com/youtube/v3/liveChat/messages?part=snippet&alt=json returned "Request contains an invalid argument.". Details: "[{'domain': 'youtube.api.v3.LiveChatMessageInsertResponse.Error', 'reason': 'ERROR_UNSPECIFIED'}]">
I have been following the API documentation found at https://developers.google.com/youtube/v3/live/docs/liveChatMessages/insert and https://developers.google.com/resources/api-libraries/documentation/youtube/v3/python/latest/youtube_v3.liveChatMessages.html#insert

I've had this same problem with Dart instead of Python:
await youTubeApi!.liveChatMessages.insert(
LiveChatMessage(
snippet: LiveChatMessageSnippet(
liveChatId: chatId,
type: "textMessageEvent",
textMessageDetails: LiveChatTextMessageDetails(messageText: message)))
Resulting in the "400 Request contains an invalid argument" error.
The solution was simple: I forgot to activate the YouTube channel of the account. Check whether you can write into the chat manually.

Related

Discord bot returns error when using slash commands with Lambda and API Gateway

I'm building a Discord bot using Lambda and API Gateway, and I'm trying to integrate it with Discord using the INTERACTIONS ENDPOINT URL. I've set up the slash commands using the following script:
import json
import requests
APPLICATION_ID = "x"
BOT_TOKEN = "x"
GUILD_ID = "x"
HEADERS = {"Authorization": f"Bot {BOT_TOKEN}"}
URL = f"https://discord.com/api/v10/applications/{APPLICATION_ID}/guilds/{GUILD_ID}/commands"
json_file = {
"name": "hello",
"type": 1,
"description": "replies with bar;/"
}
r = requests.post(URL, headers=HEADERS, json=data)
The bot is deployed and seems to be working fine, as it's syncing correctly with Discord and appears connected on my server. However, when I try to execute a /hello, I get the following error:
Cosmic Cat:
This interaction failed
I have checked the logs from my Lambda function and there are no errors or exceptions being thrown, even though the logs show that the correct commands should be executed. Here is some of those logs:
2022-12-13T14:59:34.807-03:00 START RequestId: 58f5bfc7-a85a-494c-a92b-9f746d401ce9 Version: $LATEST
2022-12-13T14:59:34.808-03:00 event: {'rawBody': '{"app_permissions":"...'resource-path': '/discord'}}
2022-12-13T14:59:34.808-03:00 [*] running command...
2022-12-13T14:59:34.808-03:00 command hello
2022-12-13T14:59:34.808-03:00 [*] detected hello. Executing...
2022-12-13T14:59:34.809-03:00 END RequestId: 58f5bfc7-a85a-494c-a92b-9f746d401ce9
I have tried troubleshooting the issue by rejoining the bot on the server, adding more logs on Lambda execution, removing and adding API Gateway on INTERACTIONS ENDPOINT URL, but have not been able to resolve the problem. Any suggestions on how to fix this issue would be greatly appreciated.
My repository can be found here: https://github.com/crisdevnull1/cosmic-cat-bot
And the link of the tutorial that I followed: https://oozio.medium.com/serverless-discord-bot-55f95f26f743

Connecting to ConnectWise API in Python

I'm trying to connect to the ConnectWise API using Python, but I keep running into "400 Client Error: Bad Request" errors.
When I use "https://api-na.myconnectwise.net/v4_6_version/apis/3.0/" as the url, I get an "invalid token" message, and when I use the codebase shown in my company info as opposed to "v4_6_version," I get a message that says
"code": "ConnectWiseApi", "message": "UserNotAuthenticated", "errors": null"
Has anyone run into these sorts of problems? From what I've found, it seems like this is caused by incorrect public/private keys, but I've tried with several different keys and keep getting the same message. I think it might be my url that's wrong, but I'm not sure.
Three components you need:
header called "clientid" with the value of your client ID from here
https://developer.connectwise.com/ClientID
basic authentication username = company+public key
basic authentication password = private key
I was able to get 200OK response trying to authenticate as above with Postman

formatting message from sns publish to https endpoints

I am publishing messages to a sns_topic and am suing boto3.
I am using https endpoint as protocol. The output message received to the endpoint are included with "/". I tried a way to escape that by doing this
def sns_publish(message, sns_event):
try:
topic_arn = get_topic_arn(sns_event)
customer_id = str(message['customer_id'])
message = json.dumps({"default":json.dumps(message)})
sns_client.publish(TopicArn=topic_arn,
Message=message,
MessageStructure='json',
MessageAttributes={
'customer_id': {
'DataType': 'String',
'StringValue': customer_id
}})
except Exception as e:
logging.exception("SNSPublishError: {}".format(e))
output received to https endpoint is below:
"Message": "{\"id\": \"WT3375104\", \"bill_to_nbr_x\": \"7159\", \"file_nbr_x\": \"3375104\"}"
I followed the boto3 documentation and gave Message and MessageStructure attributes as shown above in the code, how can I remove those "/" from JSON output
it's aws feature to present sent data in such format, so to parse it use json module:
import json
mess = {"Message": "{\"id\": \"WT3375104\", \"bill_to_nbr_x\": \"7159\", \"file_nbr_x\": \"3375104\"}"}
print(json.loads(mess['Message']))
Have you tried using raw message delivery? This should result in the message not looking like an SNS message, which means the message doesn't need to be escaped because it's not included in another JSON object.

Python twitter package : get error code

I'm not yet very familiar with error handling in Python. I'd like to know how to retrieve the error code when I get an error using the python-twitter package :
import twitter
#[...]
try:
twitter_connexion.friendships.create(screen_name = "someone_who_blocked_me", follow = True)
except twitter.TwitterHTTPError as twittererror:
print(twittererror)
Twitter sent status 403 for URL: 1.1/friendships/create.json using parameters: (follow=True&oauth_consumer_key=XXX&oauth_nonce=XXX&oauth_signature_method=HMAC-SHA1&oauth_timestamp=XXX&oauth_token=XXX&oauth_version=1.0&screen_name=someone_who_blocked_me&oauth_signature=XXX)
details: {'errors': [{'message': 'You have been blocked from following this account at the request of the user.', 'code': 162}]}
In this case, I'd like to retrieve the 'code': 162 part, or just the 162.
twittererror.args is a tuple with one element in it, which is a string, print(twittererror.args[0][0:10]) outputs Twitter se
How can I get the 162 ?
(Obviously, twittererror.args[0][582:585] is not the answer I'm looking for, as any other error message will be of a different length and the error code won't be at [582:585])
Looking at how the TwitterHTTPError is defined in this GitHub repo, you should obtain the dict with twittererror.response_data.
Therefore you can do something like that:
import twitter
#[...]
try:
twitter_connexion.friendships.create(screen_name = "someone_who_blocked_me", follow = True)
except twitter.TwitterHTTPError as twittererror:
for error in twittererror.response_data.get("errors", []):
print(error.get("code", None))

Can't make GAE Channel API work on local computer

I am creating a small application to test how GAE Channel API works. I think I have done all as it's described in the documentation but when I launch it, it shows an error in FireFox error log about syntax in the beginning and then another repeating error that an element wasn't found that.
Here is the first error info:
Source: http://127.0.0.1:8080/_ah/channel/dev?command=connect&channel=channel-773698929-185804764220139124118
Line 1, symbol 1
Here is the url where my javascript code tries to connect repeatedly and it raises the second error:
http://127.0.0.1:8080/_ah/channel/dev?command=poll&channel=channel-2071442473-185804764220139124118&client=1
I get the token through a JSON request with jQuery $.get. Then I run this code to get the token and open the channel. The error begins to show just when I run socket = channel.open(handler):
var response = JSON.parse(data);
var token = response.token.toString();
channel = new goog.appengine.Channel(token);
var handler = {
'onopen': onOpened,
'onmessage': onMessage,
'onerror': function() {
},
'onclose': function() {
}
};
socket = channel.open(handler);
Here is the server side code in Python to open the channel:
class OpenChannel(webapp.RequestHandler):
def get(self):
user = users.get_current_user()
token = channel.create_channel(user.user_id())
serialized = json.dumps({'token': token})
self.response.headers['Content-Type'] = "application/json"
self.response.out.write(serialized)
What's my error and what can I do? Thanks!
It seems that Channel API works on localhost different way than on GAE hosting. I uploaded it to the cloud and it works well now. Though it looks like it working fine on the local computer, it shows permanent JS error repeating in the error log.
You could try removing the handler argument and adding the handlers as methods of the socket object i.e. socket.onopen = function() {}; etc. That worked for me. But you are right. According to this, you should be able to get this working by using the handler argument. Hmm.

Categories