how to use twilio video api python? - django

I would like to implement twilio video API in my Django project but i didn't really understand the documentation. I managed to create a room following this example:
from twilio.rest import Client
api_key_sid = "SKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
api_key_secret = "your_api_key_secret"
client = Client(api_key_sid, api_key_secret)
room = client.video.rooms.create(unique_name='DailyStandup')
print(room.sid)
What should I do after that? How can I access the room and start the chat?

Related

twilio api sms notifications with python django

Good evening everyone I had to implement the twilio module in my django project and it works well, the problem is that it does not allow you to send sms to phone numbers other than mine
I think sample code is like the following. You need set the two environment variables TWILIO_ACCOUNT_SID and TWILIO_AUTH_TOKEN.
import os
from twilio.rest import Client
account_sid = os.environ['TWILIO_ACCOUNT_SID']
auth_token = os.environ['TWILIO_AUTH_TOKEN']
client = Client(account_sid, auth_token)
message = client.messages.create(
body="your message",
from_='+15017122661',
to='+15558675310'
)
print(message.sid)

How do I register Google Classroom API for push notifications?

I want to create a program that will receive notifications from my Google Classroom in question, and do something with that data. How can I register Google Classroom to react to an event?
I haven't made anything yet, and I don't know anything about Google's APIs. What should I do?
The process of registering the Google Classroom API for push notifications includes authentication, authorization, and parsing a request to Google to tell your Classroom to send these push notifications.
I highly recommend you have basic knowledge of the Google Cloud platform in the Java programming language, unlike me when I tried to do this. Trust me... it wasn't fun.
I do believe you will understand this concept enough to be able to transfer it to your language of choice, I did this in Java, using IntelliJ IDEA as my IDE.
Apart from the Google Classroom API, Google features another service to their collection called "Pub/Sub". Pub/Sub stands for Publisher/Subscriber. If you're familiar with how a queue works, think of Pub/Sub as a sort of refined queue system. You have a publisher, who posts messages on a "topic", and a subscriber to the topic who will pull messages from the topic, and choose to "acknowledge" the message or not. Acknowledging a message deletes it from the queue. For example, the publisher code sends the message "Hello, World" to a topic. That message will stay in the topic until a subscriber to that topic chooses to pull the message, read "Hello, World", and acknowledge the message, so it doesn't pop up again when pulling messages. The publisher can send as many messages as it wants. The publisher can send 10 messages, and the subscriber can choose to pull them all and iterate through them or just a few at a time.
This applies to this system because you're going to use a built-in function of the Google Classroom API that allows the API to act as a "publisher" and send update messages to a topic of your choosing. Then, you'll have a separate application checking for updates whenever you'd wish. To simplify it for now, you tell the Classroom API to "Please send update messages to this topic. I only want updates when the teacher edits the course work catalog in any way". This request will be followed by the Classroom API and the program will send messages to your topic whenever a teacher edits, or posts, or deletes, and such more.
If your classroom publisher sent 5 updates in a day, you'll have 5 pullable messages sent to your topic that any subscribing program of that topic can pull and acknowledge.
If you do not understand enough, in your opinion. Please, please do some research on Google Cloud Pub/Sub before continuing, since doing this basically revolves around this service.
Let's do this step-by-step...
Create a new project
Enable Classroom API and PubSub API
Enable Billing
Go to "IAM & admin"
Give the owner permission to "classroom-notifications#system.gserviceaccount.com"
Set up credentials for Classroom API and a "UI-based platform" using "User data"
Set up the consent screen. Just add an application name for now.
Create credentials as an "OAuth Client ID"
Choose Application Type > Other. Don't mind the client name
Download the JSON file. Rename it to "credentials_temp.json"
Create a Gradle based Java project (I'm using IntelliJ). Group id: temp. Artifact id: temp. Project name: temp
Add this to build.gradle under "dependencies"
compile 'com.google.api-client:google-api-client:1.23.0'
compile 'com.google.oauth-client:google-oauth-client-jetty:1.23.0'
compile 'com.google.apis:google-api-services-classroom:v1-rev135-1.23.0'
Set the sourceCompatibility variable in build.gradle to 11
Import those changes (There may be a little box at the bottom-right saying "import changes" as an option)
Put the credentials file in src/main/resources
In src/main/java, make a new class. Name it "TempTest.java"
Use this code I've written for you
import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp;
import com.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver;
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow;
import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.client.util.store.FileDataStoreFactory;
import com.google.api.services.classroom.Classroom;
import com.google.api.services.classroom.model.*;
import java.io.*;
import java.security.GeneralSecurityException;
import java.util.ArrayList;
import java.util.List;
import static com.google.api.services.classroom.ClassroomScopes.all;
public class TempTest {
private static final String APPLICATION_NAME = "Google Classroom API Java Quickstart";
private static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();
private static final String TOKENS_DIRECTORY_PATH = "tokens";
private static final String CREDENTIALS_FILE_PATH = "/credentials.json";
private static List<String> SCOPES = new ArrayList<>();
private static Classroom service;
private static String TOPIC_NAME = "projects/temp-260404/topics/temp";
private static String COURSE_ID = "47737005203";
static {
SCOPES.addAll(all());
}
public static void main(String... args) throws IOException, GeneralSecurityException {
final var HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
service = buildClassroomService(HTTP_TRANSPORT);
// registerForPushNotifications();
List<Course> courses = getAllCourses();
if (courses == null || courses.size() == 0)
System.out.println("No courses found.");
else {
System.out.println("\nCourses:");
for (var currentCourse : courses)
System.out.println(currentCourse.getName() + "(" + currentCourse.getId() + ")");
}
}
private static void registerForPushNotifications() throws IOException {
final var pubSupTopic = new CloudPubsubTopic()
.setTopicName(TOPIC_NAME);
final var courseWorkChangesInfo = new CourseRosterChangesInfo()
.setCourseId(COURSE_ID);
final var feed = new Feed()
.setFeedType("COURSE_WORK_CHANGES")
.set("courseWorkChangesInfo", courseWorkChangesInfo);
Registration notificationsRegistration = new Registration()
.setFeed(feed)
.setCloudPubsubTopic(pubSupTopic);
pubSupTopic.setFactory(JSON_FACTORY);
courseWorkChangesInfo.setFactory(JSON_FACTORY);
feed.setFactory(JSON_FACTORY);
notificationsRegistration.setFactory(JSON_FACTORY);
service.registrations().create(notificationsRegistration).execute();
System.out.println("Successfully registered");
}
private static Classroom buildClassroomService(final NetHttpTransport HTTP_TRANSPORT) throws IOException {
final var serviceCredentials = getCredentials(HTTP_TRANSPORT);
return new Classroom.Builder(HTTP_TRANSPORT, JSON_FACTORY, serviceCredentials)
.setApplicationName(APPLICATION_NAME)
.build();
}
private static Credential getCredentials(final NetHttpTransport HTTP_TRANSPORT) throws IOException {
final var clientSecrets = loadJSONClientSecrets();
final var dataStoreFactory = new FileDataStoreFactory(new File(TOKENS_DIRECTORY_PATH));
final var authenticationFlow = new GoogleAuthorizationCodeFlow.Builder(
HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, SCOPES)
.setDataStoreFactory(dataStoreFactory)
.setAccessType("offline")
.build();
return redirectToAuthentication(authenticationFlow);
}
private static GoogleClientSecrets loadJSONClientSecrets() throws IOException {
final var credentialFileStream = getCredentialsJSONFile();
if (credentialFileStream == null)
throw new FileNotFoundException("Resource not found: " + CREDENTIALS_FILE_PATH);
return GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(credentialFileStream));
}
private static InputStream getCredentialsJSONFile() {
return TempTest.class.getResourceAsStream(CREDENTIALS_FILE_PATH);
}
private static Credential redirectToAuthentication(GoogleAuthorizationCodeFlow flow) throws IOException {
final var receiver = new LocalServerReceiver.Builder().setPort(8888).build();
return new AuthorizationCodeInstalledApp(flow, receiver).authorize("user");
}
private static List<Course> getAllCourses() throws IOException {
ListCoursesResponse response = service.courses().list()
.execute();
return response.getCourses();
}
}
Go to Google Classroom and create your own Classroom for testing purposes.
Go to Pub/Sub and create a new topic. Make sure it's set to "Google managed key". Get its name under "Topic name" when it's made. There is a little button for copying the full path.
Set the TOPIC_NAME field of the class to a String containing the topic name you just copied
Run the code and authorize with all scopes. You will be redirected. Make sure you choose the same account you use Cloud Platform on.
Running it will give you a list of your courses and their ID numbers in parentheses. Copy the ID number of the test course you made. It should be outputted to the console after running your code.
Set the COURSE_ID field of the class to a String containing the ID you just copied
Uncomment line 40 and run the code again
You're done with my example
What you just did was authenticate yourself so Google Knows what permissions you're giving it, and it can verify your identity. Then, you sent a JSON request to Google with information about what topic you want updates to be published to, the type of updates to get, and the specific classroom to get these updates from.
I highly, HIGHLY recommend you learn how the structure of the JSON response works here.
Perhaps start here.
This page on the Google documentation has decent information. It also shows the JSON formatting of the message you'll pull from another program using the Google Pub/Sub API. I have not included that here.
Thank you, and good luck. Sorry, I may edit this question a few times. I'm really tired right now.

Error Pulling Facebook Ad Campaign

I am trying to automate a task for my company. They want me to pull the insights from their ad campaigns and put it in a CSV file. From here I will create a excel sheet that grabs this data and automates the plots that we send to our clients.
I have referenced the example code from the library and I believe where my confusion exists is in who I define 'me' to be in line 14.
token = 'temporary token from facebook API'
VOCO_id = 'AppID'
AppSecret = 'AppSecret'
me = 'facebookuserID'
AppTokensDoNotExpire = 'AppToken'
from facebook_business import FacebookSession
from facebook_business import FacebookAdsApi
from facebook_business.adobjects.campaign import Campaign as AdCampaign
from facebook_business.adobjects.adaccountuser import AdAccountUser as AdUser
session = FacebookSession(VOCO_id,AppSecret,AppTokensDoNotExpire)
api = FacebookAdsApi(session)
FacebookAdsApi.set_default_api(api)
me = AdUser(fbid=VOCO_id)
####my_account = me.get_ad_account()
When I run the following with the hashtag on my_account, I get a return stating that the status is "live" for these but the value of my permissions is not compatible.

How to use google contacts api to allow my users to invite their gmail contacts to my django website

I have a website built in django 1.7, python 3.4. I want to enable my users to invite their gmail contacts to my website (like linkedin & many other websites do). I am using Oauth2.0 and am able to get permission to access their contacts. But i am not getting an idea how to proceed and what steps to take.
Can somebody help me to get an overview of all the steps that i need to take and a little explanation as to how to do that.
Even a link to suitable post would be helpful.
See, When you need to implement these features in your website, you will have to understand the APIs etc to utilize it to the fullest.
Go through this https://developers.google.com/google-apps/contacts/v3/?csw=1#audience
Let's talk only about google only. The rest providers can also be managed with similar steps. Here you are using django-allauth for this task.
The basic steps involved are:
Get your app created and configured with the provider. for that you will need a developer profile in google(or facebook etc.). You will have to create an app in google developer console and you will find a plenty of tutorial for this on internet. That has been done by you as you have signup with google activated on your site. That is server side of Oauth2.0
Now you need to define the scope of authorization you need. You might only need the access to view the public profile thing. that may include first name, last name, email, id, gender, etc. For your app, you need contacts of users and for that you will have to include it in the scope too.
That is done in settings.py only.
'google': {'SCOPE': ['profile', 'email', 'https://www.googleapis.com/auth/contacts'],
'AUTH_PARAMS': {'access_type': 'online'}}
}
Now here, you have got the access to the contacts. Now, you only need to extract the contacts with the consent of data owner(user).
For this purpose,you may follow the first link in the answer. What you have to do is you have to send a get request to some url('https://www.google.com/m8/feeds/contacts/default/full' + '?access_token=' + access_token). The request goes to provider only(google) with the authorization token it has provided you for that particular user. That you will find in the db table socialtoken. Once you send proper request, the response you will get is the contacts of the user in xml format.
Once you get it, you can easily parse it to extract the required information.
Things are simple if you understand the flow. django-allauth only helpy you upto signup & signin where you can get different permissions through defining the scope.
For extracting the contacts, you can write your own code.
A simple example is:
def get_email_google(request):
# social = request.user.social_auth.get(provider='google-oauth2')
user =request.user
# Code dependent upon django-allauth. Will change if we shift to another module
# if request.user.userprofile.get_provider() != "google":
a = SocialAccount.objects.get(user=user)
b = SocialToken.objects.get(account=a)
# access = b.token
access_token = b.token
url = 'https://www.google.com/m8/feeds/contacts/default/full' + '?access_token=' + access_token + '&max-results=100'
req = urllib2.Request(url, headers={'User-Agent' : "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/534.30 (KHTML, like Gecko) Ubuntu/11.04 Chromium/12.0.742.112 Chrome/12.0.742.112 Safari/534.30"})
contacts = urllib2.urlopen(req).read()
contacts_xml = etree.fromstring(contacts)
# print
# return render(request, 'search/random_text_print.html', locals())
result = []
for entry in contacts_xml.findall('{http://www.w3.org/2005/Atom}entry'):
for address in entry.findall('{http://schemas.google.com/g/2005}email'):
email = address.attrib.get('address')
result.append(email)
return render(request, 'search/random_text_print.html', locals())
user =request.user
a = SocialAccount.objects.get(user=user)
b = SocialToken.objects.get(account=a)
# access = b.token
access_token = b.token
SCOPES = ['SCOPE_URL']
creds = client.AccessTokenCredentials(access_token, 'USER_AGENT')
service = build('calendar', 'v3', credentials=creds)

How to retrieve a person's profile picture from FB with Flask?

I have already managed to get all the basic information from the user but I have no idea how to retrieve his/her profile picture.
me = facebook.get('/me?fields=id,name,first_name,last_name,age_range,link,gender,locale,timezone,updated_time,verified,friends,email')
Can you please provide some hints? I am using Python Flask and OAuth.
Try adding 'picture' to your list of parameters
With OAtuh and Facebook Graph you can use this, like you see this code is C# based, but you just need to check the requests URL's:
request = WebRequest.Create("https://graph.facebook.com/v2.3/me/picture?access_token=" + Uri.EscapeDataString(authorization.AccessToken));
using (var response = request.GetResponse())
{
myImageBoxOrSomethingThatAcceptUrl.PictureUrl = response.ResponseUri.AbsoluteUri;
}