12200 - Schema validation warning twilio - twilio

Hi team i need to fix the 12200 - Schema validation warning twilio.
everything is working but i dont receive the whatsapp respond back .
enter image description here
here is the app.py code:
from helper.openai_api import text_complition
from helper.twilio_api import send_message
from twilio.twiml.messaging_response import MessagingResponse
from flask import Flask, request
from dotenv import load_dotenv
load_dotenv()
app = Flask(__name__)
#app.route('/')
def home():
return 'All is well...'
#app.route('/twilio/receiveMessage', methods=['POST'])
def receiveMessage():
try:
message = request.form['Body']
sender_id = request.form['From']
# Placeholder code
result = {}
result['status'] = 1
result['response'] = "Hi, I'm CODAI, I have received your message."
send_message(sender_id, result['response'])
except:
pass
return 'OK', 200
here is the openai.py code:
import os
import openai
from dotenv import load_dotenv
from twilio.twiml.messaging_response import MessagingResponse
load_dotenv()
openai.api_key = os.getenv('OPENAI_API_KEY')
def text_complition(prompt: str) -> dict:
'''
Call Openai API for text completion
Parameters:
- prompt: user query (str)
Returns:
- dict
'''
try:
response = openai.Completion.create(
model='text-davinci-003',
prompt=f'Human: {prompt}\nAI: ',
temperature=0.9,
max_tokens=150,
top_p=1,
frequency_penalty=0,
presence_penalty=0.6,
stop=['Human:', 'AI:']
)
return {
'status': 1,
'response': response['choices'][0]['text']
}
except:
return {
'status': 0,
'response': ''
}
here is the twilio.py code:
import os
from twilio.twiml.messaging_response import MessagingResponse
from twilio.rest import Client
from dotenv import load_dotenv
load_dotenv()
account_sid = os.getenv('TWILIO_ACCOUNT_SID')
auth_token = os.getenv('TWILIO_AUTH_TOKEN')
client = Client(account_sid, auth_token)
def send_message(to: str, message: str) -> None:
'''
Send message through Twilio's WhatsApp API.
Parameters:
- to(str): recipient's phone number in the format of "whatsapp:+[country code][phone number]"
- message(str): text message to send
Returns:
- None
'''
_ = client.messages.create(
from_=os.getenv('FROM'),
body=message,
to="whatsapp:" + to
)
i need help to fix the error 12200 - Schema validation warning twilio

Related

Static type checking The variable jiraHelper/issue is undeclared

I am using a condition in my script in the REST endpoint and I am receiving the following errors:
Anyone knows what the problem is and what needs to be fixed?
Here is the code:
package CreateMultipleSubtasks
import org.apache.log4j.Logger
import com.atlassian.jira.plugin.webfragment.model.JiraHelper
import com.atlassian.jira.component.ComponentAccessor
def log1 = Logger.getLogger("atlassian-jira.log")
log1.warn("MOUNA BEFORE")
Configuration_CreateMultipleSubtasks conf = new Configuration_CreateMultipleSubtasks()
def subTaskCreatorHashMap= conf.getSubTaskCreatorHashMap()
String projectKey = subTaskCreatorHashMap["projectKey"];
String issueTypeName = subTaskCreatorHashMap["issueTypeName"];
log.warn("MOUNA PROJECT KEY "+ projectKey+" issuetypename "+issueTypeName)
def val=jiraHelper.project?.key==projectKey && issue.issueType.name==issueTypeName
return val

How to send result of function from Django Server to React Native App?

I am study React Native and Django Development and I create an app which recognize a text from image. I realized POST method from React Native to Django Server but I don't understand how to send the result of recognition back to React.
How I can resolve this problem?
Django Server:
views.py:
from .serializers import PostSerializer
from .models import Ocr
from rest_framework.views import APIView
from rest_framework.parsers import MultiPartParser, FormParser
from rest_framework.response import Response
from rest_framework import status
# Create your views here.
from django.http.response import JsonResponse
# Create your views here.
# import pytesseract to convert text in image to string
import pytesseract
# import summarize to summarize the ocred text
from .forms import ImageUpload
import os
# import Image from PIL to read image
from PIL import Image
from django.conf import settings
# Create your views here.
class PostView(APIView):
parser_classes = (MultiPartParser, FormParser)
def get(self, request, *args, **kwargs):
posts = Ocr.objects.all()
serializer = PostSerializer(posts, many=True)
print(serializer.data)
return Response(serializer.data)
def post(self, request, *args, **kwargs):
posts_serializer = PostSerializer(data=request.data)
if posts_serializer.is_valid():
text = ""
message = ""
posts_serializer.save()
try:
posts_serializer.save()
image = request.FILES['image']
image = image.name
path = settings.MEDIA_ROOT
pathz = path + "/images/" + image
text = pytesseract.image_to_string(Image.open(pathz), lang='rus+eng')
os.remove(pathz)
except Exception:
message = "check your filename and ensure it doesn't have any space or check if it has any text"
context = {
'text': text,
'message': message
}
print(context)
return Response(posts_serializer.data, status=status.HTTP_201_CREATED)
else:
return Response(posts_serializer.errors, status=status.HTTP_400_BAD_REQUEST)
React-Native:
CameraScreen.js:
const postToServer = (img) => {
const formData = new FormData();
formData.append('image', {
uri: img.uri,
type: 'image/jpeg',
name: 'test.jpg',
})
formData.append('title', 'title');
fetch('http://192.168.0.149:8000/api/textocr/', {
method: 'POST',
body: formData,
// If you add this, upload won't work
headers: {
'Accept': 'application/json',
'Content-Type': 'multipart/form-data',
}
});
}

How to send and receive image as part of http form-data using requests and flask

I would like to make an http POST request, and include an image as part of the multipart/form-data. I'd like to avoid encoding this image as base64, and just send it as a binary blob, which I know that http can handle.
Here is my code on the client side:
from __future__ import print_function
import requests
import json
import cv2
def post_encoded_image(url, headers):
img = open("cyrus.jpg", 'rb').read()
payload = {'image': img, 'identity': 'cyrus'}
r = requests.post(url + "encoded-image", data=payload)
print(r)
url = "http://localhost:8080/"
content_type = 'multipart/form-data'
headers = {'content-type': content_type}
post_encoded_image(url, headers)
On the server side, my code looks like this:
from flask import Flask, request
import flask
import tfsdk
import numpy as np
from colorama import Fore
from colorama import Style
import os
import cv2
#app.route('/encoded-image', methods=['POST'])
def test():
image = request.form.get("image")
nparr = np.fromstring(image, np.uint8)
img = cv2.imdecode(nparr, cv2.IMREAD_COLOR)
print(type(img))
return "success"
if __name__ == '__main__':
app.run()
When I make the request, the server prints the type of img as NoneType, meaning the call to imdecode didn't work, meaning something strange is going on the server side with the encoded image.
What is the proper way to do this?
Edit
I was able to achieve the desired functionality by doing the following:
client:
from __future__ import print_function
import requests
import json
import cv2
def post_encoded_image(url, headers):
img = open("cyrus.jpg", 'rb').read()
file = {'image': img}
data = {'identity': 'cyrus'}
r = requests.post(url + "encoded-image", data=data, files=file)
print(r)
url = "http://localhost:8080/"
content_type = 'multipart/form-data'
headers = {'content-type': content_type}
post_encoded_image(url, headers)
Server:
#app.route('/encoded-image', methods=['POST'])
def test():
ID = request.form.get("identity")
image = request.files['image'].read()
nparr = np.fromstring(image, np.uint8)
Is this the proper way of doing it?
I was able to achieve the desired functionality as follows:
Client:
from __future__ import print_function
import requests
import json
import cv2
def post_encoded_image(url, headers):
img = open("cyrus.jpg", 'rb').read()
file = {'image': img}
data = {'identity': 'cyrus'}
r = requests.post(url + "encoded-image", data=data, files=file)
print(r)
url = "http://localhost:8080/"
content_type = 'multipart/form-data'
headers = {'content-type': content_type}
post_encoded_image(url, headers)
Server:
#app.route('/encoded-image', methods=['POST'])
def test():
ID = request.form.get("identity")
image = request.files['image'].read()
nparr = np.fromstring(image, np.uint8)

Messages in Django Channels sent outside consumer not being received

I'm trying to send messages to specific websocket instances, but neither channel_layer.send, nor using channel_layer.group_send with unique groups for each instance seems to be working, no errors are being raised, they just aren't received by the instances.
The function that sends the message is:
def listRequest(auth_user, city):
request_country = city["country_name"]
request_city = city["city"]
request_location = request_city +", "+request_country
concatenate_service_email = auth_user.service + "-" + auth_user.email
this_request = LoginRequest(service_and_email=concatenate_service_email, location=request_location)
this_request.generate_challenge()
this_request.set_expiry(timezone.now() + timezone.timedelta(minutes=5))
this_request.save()
channel_layer = get_channel_layer()
print(auth_user.current_socket)
async_to_sync(channel_layer.group_send)(
auth_user.current_socket,{
"type": "new.request",
"service_and_email" : concatenate_service_email
},
)
My current working consumers.py (receive and scanrequest don't have anything that's likely to be relevant to the issue):
from asgiref.sync import async_to_sync
from channels.generic.websocket import WebsocketConsumer
from .helpers import verify_identity, unique_group
from django.utils import timezone
from .models import Authentication, LoginRequest
import json
import time
class AuthConsumer(WebsocketConsumer):
account_list =[]
def connect(self):
print("Connect attempted")
print(self.channel_name)
print(unique_group(self.channel_name))
async_to_sync(self.channel_layer.group_add)(unique_group(self.channel_name), self.channel_name)
self.accept()
def disconnect(self, close_code):
print("Disconnect attempted")
async_to_sync(self.channel_layer.group_discard)(unique_group(self.channel_name), self.channel_name)
for i in self.account_list:
serviceEmailSplit = i.split("-")
try:
auth_user = Authentication.objects.get(service=serviceEmailSplit[0],email=serviceEmailSplit[1])
auth_user.set_socket("NONE")
auth_user.save()
except:
print("Error user %s does not exist" %i)
pass
def receive(self, text_data):
print("Receiving data")
if text_data[0:7] == "APPROVE":
data_as_list = text_data.split(",")
serviceEmailSplit = data_as_list[1].split("-")
auth_user = Authentication.objects.get(service=serviceEmailSplit[0],email=serviceEmailSplit[1])
this_request = LoginRequest.objects.get(service_and_email=data_as_list[1],approved=False, expiry__gt=timezone.now())
if verify_identity(auth_user.public_key, data_as_list[2], this_request.challenge):
this_request.set_approved()
self.send("Request Approved!")
else:
self.send("ERROR: User verification failed")
else:
self.account_list = text_data.split(",")
self.account_list.pop(-1)
print(self.account_list)
for i in self.account_list:
serviceEmailSplit = i.split("-")
try:
auth_user = Authentication.objects.get(service=serviceEmailSplit[0],email=serviceEmailSplit[1])
auth_user.set_socket(unique_group(self.channel_name))
auth_user.save()
except:
self.send("Error user %s does not exist" %i)
self.scanRequest()
def scanRequest(self):
requestSet = LoginRequest.objects.filter(service_and_email__in = self.account_list, approved = False, request_expiry__gt = timezone.now())
if requestSet.count() > 0:
for request in requestSet:
self.send(request.service_and_email+","+request.location+","+str(request.challenge))
else:
self.send("NOREQUESTS")
def new_request(self,event):
print("NEW REQUEST!")
this_request = LoginRequest.objects.filter(service_and_email = event["service_and_email"]).latest('request_expiry')
self.send(this_request.service_and_email+","+this_request.location+","+str(this_request.challenge))
And my routing.py:
from django.urls import re_path
from . import consumers
from django.conf.urls import url
websocket_urlpatterns = [
url(r"^ws/$", consumers.AuthConsumer.as_asgi()),
]
"NEW REQUEST!" is never printed, having tried to call it both by sending a message directly, and neither does using groups like I have written above.
My redis server appears to be working from testing like the documentation for the channels tutorial suggests:
https://channels.readthedocs.io/en/stable/tutorial/part_2.html
I'm pretty stumped after attempts to fix it, and I've looked at the other posts on stackoverflow with the same/similar issues and I'm already following whatever solutions they have in my code.

JIRA do I have a way to get the list all ID of my transition steps?

I want to synchronize between two systems. However, to update the transition status of the bug I have to send a JSON file with my arguments (new status) something like this:
{
"update": {
"comment": [
{
"add": {
"body": "Comment added when resolving issue"
}
}
]
},
"transition": {
"id": "5"
}
}
To set a new status I have to set it's id, How can I get the list of all the IDs and the description of each one.
You can get a list of the transitions possible for this issue by the current user, along with fields that are required and their types by url /rest/api/2/issue/{issueIdOrKey}/transitions (get request)
You can use the following python script to get the information you want.
#!/usr/bin/env python
from __future__ import print_function
import ConfigParser
import requests
import json
import base64
import sys
def print_error(*args, **kwargs):
print(*args, file=sys.stderr, **kwargs)
def get_issue(user,password,search_url):
user_auth = base64.b64encode(user+':'+password)
headers = {'Authorization': 'Basic ' + user_auth}
return requests.get(search_url, headers=headers)
def main():
if len(sys.argv) < 2:
usage_message = 'Usage: ' + sys.argv[0] + ' issue_number'
print_error(usage_message)
sys.exit(1)
config = ConfigParser.RawConfigParser()
config.read('config.properties')
jira_user = config.get('Global', 'jira_user')
jira_pass = config.get('Global', 'jira_pass')
jira_base_url = config.get('Global', 'jira_base_url')
issue_url = config.get('Global', 'issue_url')
issue = sys.argv[1]
issue_search_url = jira_base_url + issue_url + issue + '/transitions'
response = get_issue(jira_user,jira_pass,issue_search_url)
if response.status_code == 404:
print_error(issue + ' NOT FOUND!')
sys.exit(1)
data = response.json()
for transition in data['transitions']:
print("%s %s" % (transition['id'], transition['name']))
main()
You need to have a configuration file (config.properties) in the same directory as the script with the following content:
[Global]
jira_user=username
jira_pass=pass
jira_base_url=http://your_jira_url.com
issue_url=/rest/api/2/issue/
Then you call the script like this:
./get_transitions.py your_ticket_number

Resources