I am not able to insert full url in Kingsoft Writer - hyperlink

Here is my url which i have to insert/make hyperlink of .
http://192.168.10.183:8080/xyzadsfgrghrh//Request?Key=eform_renderer&OwnerType=Prj&OwnerID=79061&ItemType=Aci&ItemID=20032785&ActionToPerform=View&PopupMode=Y&WindowOpenOnSave=Y&ALLOWREADACCESS=Y&FromECRGetUrl=Y&GetUrlReqParams=&ParentItemId=20032785&childProcessId=qq0k5l04Gd92FFB384jODPfA93D93D.
The limit is of 255 characters.So how can i insert such a long url in my Kingsoft Writer ?

To get the shortened url dynamically from google API, first go here create your key or alternatively you can create one from credentails page for authorization so that google can verify you can send the shortened url.
Here is the sample code in python as how to proceed:
import requests
url = "https://www.googleapis.com/urlshortener/v1/url?key=YOUR_KEY"
headers = { 'Content-Type': 'application/json'}
payload = {"longUrl": "YOUR URL"}
r = requests.post(url, headers= headers, json=payload)
After success you will receive response like as mentioned on google-
{
"kind": "urlshortener#url",
"id": "YOUR SHORTENED URL",
"longUrl": "YOUR LONG URL"
}
Hope it helps.

Related

Discord OAuth2 throws Missing Permissions error when I already granted it the right permissions

Literally every single post I see when I search this is about a bot. If you are here for a bot error leave, this is not about a bot.
I am trying to create a bot that allows users to join a server from OAuth2, and I already have the access token (which works) and I am able to successfully get their user id and everything. However, when I try to join a server it immediately throws the error '{"message": "Missing Permissions", "code": 50013}'.
OAuth link: https://discord.com/oauth2/authorize?client_id=1044368734988546068&redirect_uri=*****&response_type=code&scope=identify%20guilds.join
^ The link above works fine, it's just when I try to use it to join a server, it throws the issue.
my code:
def add_to_guild(access_token, guildID, userID):
url = f"{API_ENDPOINT}/guilds/{guildID}/members/{userID}"
data = {
"access_token": access_token,
}
headers = {
"Authorization": f"Bot {TOKEN}",
'Content-Type': 'application/json'
}
r = requests.put(url=url, headers=headers, json=data)
return r.text
PLEASE help me with this. Thank you

Twitter User Lookup Request Error Confusion

I have activated my app after getting approval of my Twitter developer account. I am trying to get twitter account associated with an email/phone number using Twitter Api.
It works perfect with params like screen_name,user_id but while trying email or phone number as a param the
Response says :
Could Not Authenticate you
Code is
import requests
url = "https://api.twitter.com/1.1/users/lookup.json?map=true&phone=1234567890"
payload = {}
headers = {
'Authorization': 'OAuth realm="http%3A%2F%2Fapi.twitter.com",oauth_consumer_key="<consumer_key>",oauth_token="<outh_token>",oauth_signature_method="HMAC-SHA1",oauth_timestamp="1595318479",oauth_nonce="<nonce>",oauth_version="1.0",oauth_signature="<sig>"'
}
response = requests.request("GET", url, headers=headers, data = payload)
print(response.text.encode('utf8'))
Response :
{
"errors": [
{
"code": 32,
"message": "Could not authenticate you."
}
]
}
What are the reasons and suggestions on this ?
Will appreciate the positive feedback.
Have you tried using dynamic values generation for header like nonce generation, Timestamp, base_url according to query paramters?
It is not possible to use email or phone number as query parameters on the Twitter API. This is not supported as a feature in the API. See the documentation for supported parameters on users/lookup and users/search.

ESP8266 Micropython Twilio API

Has anyone had success using Twilio with Micropython on an 8266? I've tested the below in pyton3 and can get it to successfully send a text message. However, when I port it over to micropython (below), the message fails. I went back to the urequests library, which is where I'm getting the failure, and saw that its failing because its passing the data as a dictionary (it fails on row 79). I tried changing it to pass as a string, but then it seems the data isn't sent to Twilio.
Python3 Implementation
import requests
account_sid = "sid"
auth_token = "token"
url = "https://api.twilio.com/2010-04-01/Accounts/" + account_sid + "/Messages.json"
data = {'From': '+18005551234', 'To': '+18005551234', 'Body': 'Text Message'}
try:
resp = requests.post(url=url, data=data, auth=requests.auth.HTTPBasicAuth(account_sid, auth_token))
print(resp.status_code)
except Exception as exc:
print("\nException occured.")
sys.print_exceptin(exc)
Micropython Implementation
import urequests
import ubinascii
account_sid = "sid"
auth_token = "token"
url = "https://api.twilio.com/2010-04-01/Accounts/" + account_sid + "/Messages.json"
data = {'From': '+18005551234', 'To': '+18005551234', 'Body': 'Text Message'}
login = ubinascii.b2a_base64(account_sid.encode('utf8') + b':' + auth_token.encode('utf8'))
headers = {'Authorization': b'Basic ' + login, 'Content-Type': 'application/x-www-form-urlencoded', 'WWW - Authenticate': 'Basic realm = "Twilio API'}
try:
resp = urequests.post(url=url, data=data, headers=headers)
print(resp.status_code)
except Exception as exc:
print("\nException occured.")
sys.print_exceptin(exc)
EDIT: So it seems that its been answered here: Sending SMS in twilio returns 21603 : A 'From' number is required, but even modifying my data, I can't get the message to actually transmit. I've modified the data field to be "To=%2B18005551234&From=%2B18005551234&Body=Test", but that seems to fail as well.
Per the excellent support at Twilio, the one line that needs to be added is
login = login[:-1]
There is a newline character at the end of the base64 encoded login and this needs to be stripped out.

Sendgrid Ruby API, Trying to send over Header content in post request

I am trying to send over a Post request to sendgrid to generate an API key for a subuser.
This is what my code currently looks like
body = JSON.parse('{
"name":"My API Key",
"scopes": [
"mail.send",
"alerts.create",
"alerts.read"
]
}')
header = {'On-Behalf-Of' => 'my#email.com'}
sg = SendGrid::API.new(api_key: ENV['SENDGRID_API_KEY'])
response = sg.client.api_keys.post(request_body: body, request_header: header)
This code generates the API but on the main account instead of the Subuser account. The header is what drives where the API key is generated and I can seem to find any sources online that how the correct syntax for sending over the header to sendgrid.
If you could please help I would really appreciate it. Thanks!
I recently had to do this. You need to set the On-Behalf-Of headers when you instantiate the client not when you make the request:
```
#send_grid = API.new(api_key: #api_key, request_headers: {
'On-Behalf-Of' => #username
})
```
Then when you make a request with #send_grid it will send on behalf of the subuser -- and the API key will not show up in the list of api keys on the parent account
If I understand correct, you want to send email "From" another user. On Behalf of is non standard way of doing things.
For eg. https://sendgrid.com/docs/Classroom/Troubleshooting/Authentication/my_emails_are_displaying_as_on_behalf_of_or_via_in_some_mail_clients.html
You may want to try setting from instead of on-behalf-of
"from": {
"email": "from_address#example.com"
},
Refer to: https://sendgrid.com/docs/API_Reference/Web_API_v3/Mail/index.html

Get title from YouTube videos

I want to extract the Title of YouTube's videos. How can I do this?
Thanks.
Easiest way to obtain information about a youtube video afaik is to parse the string retrieved from: http://youtube.com/get_video_info?video_id=XXXXXXXX
Using something like PHP's parse_str(), you can obtain a nice array of nearly anything about the video:
$content = file_get_contents("http://youtube.com/get_video_info?video_id=".$id);
parse_str($content, $ytarr);
echo $ytarr['title'];
That will print the title for the video using $id as the video's id.
Hello In python3 i founded 2 ways
1) without API KEY
import urllib.request
import json
import urllib
import pprint
#change to yours VideoID or change url inparams
VideoID = "SZj6rAYkYOg"
params = {"format": "json", "url": "https://www.youtube.com/watch?v=%s" % VideoID}
url = "https://www.youtube.com/oembed"
query_string = urllib.parse.urlencode(params)
url = url + "?" + query_string
with urllib.request.urlopen(url) as response:
response_text = response.read()
data = json.loads(response_text.decode())
pprint.pprint(data)
print(data['title'])
example results:
{'author_name': 'Google Developers',
'author_url': 'https://www.youtube.com/user/GoogleDevelopers',
'height': 270,
'html': '<iframe width="480" height="270" '
'src="https://www.youtube.com/embed/SZj6rAYkYOg?feature=oembed" '
'frameborder="0" allow="autoplay; encrypted-media" '
'allowfullscreen></iframe>',
'provider_name': 'YouTube',
'provider_url': 'https://www.youtube.com/',
'thumbnail_height': 360,
'thumbnail_url': 'https://i.ytimg.com/vi/SZj6rAYkYOg/hqdefault.jpg',
'thumbnail_width': 480,
'title': 'Google I/O 101: Google APIs: Getting Started Quickly',
'type': 'video',
'version': '1.0',
'width': 480}
Google I/O 101: Google APIs: Getting Started Quickly
2) Using Google API - required APIKEY
import urllib.request
import json
import urllib
import pprint
APIKEY = "YOUR_GOOGLE_APIKEY"
VideoID = "YOUR_VIDEO_ID"
params = {'id': VideoID, 'key': APIKEY,
'fields': 'items(id,snippet(channelId,title,categoryId),statistics)',
'part': 'snippet,statistics'}
url = 'https://www.googleapis.com/youtube/v3/videos'
query_string = urllib.parse.urlencode(params)
url = url + "?" + query_string
with urllib.request.urlopen(url) as response:
response_text = response.read()
data = json.loads(response_text.decode())
pprint.pprint(data)
print("TITLE: %s " % data['items'][0]['snippet']['title'])
example results:
{'items': [{'id': 'SZj6rAYkYOg',
'snippet': {'categoryId': '28',
'channelId': 'UC_x5XG1OV2P6uZZ5FSM9Ttw',
'title': 'Google I/O 101: Google APIs: Getting '
'Started Quickly'},
'statistics': {'commentCount': '36',
'dislikeCount': '20',
'favoriteCount': '0',
'likeCount': '418',
'viewCount': '65783'}}]}
TITLE: Google I/O 101: Google APIs: Getting Started Quickly
Using JavaScript data API:
var loadInfo = function (videoId) {
var gdata = document.createElement("script");
gdata.src = "http://gdata.youtube.com/feeds/api/videos/" + videoId + "?v=2&alt=jsonc&callback=storeInfo";
var body = document.getElementsByTagName("body")[0];
body.appendChild(gdata);
};
var storeInfo = function (info) {
console.log(info.data.title);
};
Then you just need to call loadInfo(videoId).
More informations are available on the API documentation.
One way to do this would be to retrieve the video from youtube as shown here
Then extract the title out of the atom feed sent by youtube. A sample feed is shown here
I'll lay out the process as outlined by the YouTube API v3 documentation.
Make a / login to the Google account that you want to be associated with your YouTube API use.
Create a new project at https://console.developers.google.com/apis/credentials.
On the upper left, next to the Google APIs logo, go to Select a project and Create project +.
Wait a moment for the creation to finish.
Make a new API key. You'll need it to access video info under v3.
If you're not already there, go to Credentials under the navigator on the left hand side, APIs and Services > Credentials.
Under the Credentials tab, click Create Credentials and select API key.
Copy the API key to your clipboard.
Providing a video ID and your newly created API key, go to this link to see your work in action: https://www.googleapis.com/youtube/v3/videos?id=<YOUR VIDEO ID HERE>&key=<YOUR API KEY HERE>%20&part=snippet (no angle brackets)
For more info on what you can access, see here: https://developers.google.com/youtube/v3/getting-started#partial. For convenience, I'll copy one of their examples here (Example 4). The fields and part parameters in the URL are key here.
Example
The URL is, well, what URL you can go to through your browser to check it out. In return, you should get what's under API response:.
URL: https://www.googleapis.com/youtube/v3/videos?id=7lCDEYXw3mM&key=YOUR_API_KEY
&fields=items(id,snippet(channelId,title,categoryId),statistics)&part=snippet,statistics
Description: This example modifies the fields parameter from example 3
so that in the API response, each video resource's snippet
object only includes the channelId, title,
and categoryId properties.
API response:
{
"videos": [
{
"id": "7lCDEYXw3mM",
"snippet": {
"channelId": "UC_x5XG1OV2P6uZZ5FSM9Ttw",
"title": "Google I/O 101: Q&A On Using Google APIs",
"categoryId": "28"
},
"statistics": {
"viewCount": "3057",
"likeCount": "25",
"dislikeCount": "0",
"favoriteCount": "17",
"commentCount": "12"
}
}
]
}
This gives you video info in the .json file format. If your project is to access this info through JavaScript, you may be going here next: How to get JSON from URL in Javascript?.
I believe the best way is to use youTube's gdata, and then grab info from XML that is returned
http://gdata.youtube.com/feeds/api/videos/6_Ukfpsb8RI
Update:
There is a newer API out now which you should use instead
https://developers.google.com/youtube/v3/getting-started
URL: https://www.googleapis.com/youtube/v3/videos?id=7lCDEYXw3mM&key=YOUR_API_KEY
&fields=items(id,snippet(channelId,title,categoryId),statistics)&part=snippet,statistics
Description: This example modifies the fields parameter from example 3 so that in the API response, each video resource's snippet object only includes the channelId, title, and categoryId properties.
API response:
{
"videos": [
{
"id": "7lCDEYXw3mM",
"snippet": {
"channelId": "UC_x5XG1OV2P6uZZ5FSM9Ttw",
"title": "Google I/O 101: Q&A On Using Google APIs",
"categoryId": "28"
},
"statistics": {
"viewCount": "3057",
"likeCount": "25",
"dislikeCount": "0",
"favoriteCount": "17",
"commentCount": "12"
}
}
]
}
With bash, wget and lynx:
#!/bin/bash
read -e -p "Youtube address? " address
page=$(wget "$address" -O - 2>/dev/null)
title=$(echo "$page" | grep " - ")
title="$(lynx --dump -force-html <(echo "<html><body>
$title
</body></html>")| grep " - ")"
title="${title/* - /}"
echo "$title"
// This is the youtube video URL: http://www.youtube.com/watch?v=nOHHta68DdU
$code = "nOHHta68DdU";
// Get video feed info (xml) from youtube, but only the title | http://php.net/manual/en/function.file-get-contents.php
$video_feed = file_get_contents("http://gdata.youtube.com/feeds/api/videos?v=2&q=".$code."&max-results=1&fields=entry(title)&prettyprint=true");
// xml to object | http://php.net/manual/en/function.simplexml-load-string.php
$video_obj = simplexml_load_string($video_feed);
// Get the title string to a variable
$video_str = $video_obj->entry->title;
// Output
echo $video_str;
If python batch processing script is appreciated: I used BeautifulSoup to easily parse the title from HTML, urllib to download the HTML and unicodecsv libraries in order to save all the characters from Youtube title.
The only thing you need to do is to place csv with single (named) column url with URLs of the Youtube videos in the same folder as the script is and name it yt-urls.csv and run the script. You will get file yt-urls-titles.csv containing the URLs and its titles.
#!/usr/bin/python
from bs4 import BeautifulSoup
import urllib
import unicodecsv as csv
with open('yt-urls-titles.csv', 'wb') as f:
resultcsv = csv.DictWriter(f, delimiter=';', quotechar='"',fieldnames=['url','title'])
with open('yt-urls.csv', 'rb') as f:
inputcsv = csv.DictReader(f, delimiter=';', quotechar='"')
resultcsv.writeheader()
for row in inputcsv:
soup = BeautifulSoup(urllib.urlopen(row['url']).read(), "html.parser")
resultcsv.writerow({'url': row['url'],'title': soup.title.string})
If you have youtube-dl, it's as simple as:
youtube-dl --get-title https://www.youtube.com/watch?v=dQw4w9WgXcQ
Here's some cut and paste code for ColdFusion:
http://trycf.com/gist/f296d14e456a7c925d23a1282daa0b90
It works on CF9 (and likely, earlier versions) using YouTube API v3, which requires an API key.
I left some comments and diag stuff in it, for anyone who wants to dig deeper. Hope it helps someone.
You can do using Json to get the all info about video
$jsonURL = file_get_contents("https://www.googleapis.com/youtube/v3/videos?id={Your_Video_ID_Here}&key={Your_API_KEY}8&part=snippet");
$json = json_decode($jsonURL);
$vtitle = $json->{'items'}[0]->{'snippet'}->{'title'};
$vdescription = $json->{'items'}[0]->{'snippet'}->{'description'};
$vvid = $json->{'items'}[0]->{'id'};
$vdate = $json->{'items'}[0]->{'snippet'}->{'publishedAt'};
$vthumb = $json->{'items'}[0]->{'snippet'}->{'thumbnails'}->{'high'}->{'url'};
I hope it will solve your problem.
using python i got itimport pafy url = "https://www.youtube.com/watch?v=bMt47wvK6u0" video = pafy.new(url) print(video.title)
If you are familiar with java, try the Jsoup parser.
Document document = Jsoup.connect("http://www.youtube.com/ABDCEF").get();
document.title();
Try this, I am getting name and url of each video in a playlist, you can modify this code as per your requirement.
$Playlist = ((Invoke-WebRequest "https://www.youtube.com/watch?v=HKkRbc6W6NA&list=PLz9M61O0WZqSUvHzPHVVC4IcqA8qe5K3r&
index=1").Links | Where {$_.class -match "playlist-video"}).href
$Fname = ((Invoke-WebRequest "https://www.youtube.com/watch?v=HKkRbc6W6NA&list=PLz9M61O0WZqSUvHzPHVVC4IcqA8qe5K3r&ind
ex=1").Links | Where {$_.class -match "playlist-video"}).outerText
$FinalText=""
For($i=0;$i -lt $playlist.Length;$i++)
{
Write-Output("'"+($Fname[$i].split("|")[0]).split("|")[0]+"'+"+"https://www.youtube.com"+$Playlist[$i])
}
JavaX now ships with this function. Showing a video's thumbnail and title, for example, is a two-liner:
SS map = youtubeVideoInfo("https://www.youtube.com/watch?v=4If_vFZdFTk"));
showImage(map.get("title"), loadImage(map.get("thumbnail_url")));
Example
Similarly to Matej M, but more simply:
import requests
from bs4 import BeautifulSoup
def get_video_name(id: str):
"""
Return the name of the video as it appears on YouTube, given the video id.
"""
r = requests.get(f'https://youtube.com/watch?v={id}')
r.raise_for_status()
soup = BeautifulSoup(r.content, "lxml")
return soup.title.string
if __name__ == '__main__':
js = get_video_name("RJqimlFcJsM")
print('\n\n')
print(js)
I make a little bit of reinvention of excellent Porto's answer here, and wrote this snippet on Python:
import urllib, urllib.request, json
input = "C:\\urls.txt"
output = "C:\\tracks.csv"
urls=[line.strip() for line in open(input)]
for url in urls:
ID = url.split('=')
VideoID = ID[1]
params = {"format": "json", "url": "https://www.youtube.com/watch?v=%s" % VideoID}
url = "https://www.youtube.com/oembed"
query_string = urllib.parse.urlencode(params)
url = url + "?" + query_string
with urllib.request.urlopen(url) as response:
response_text = response.read()
try:
data = json.loads(response_text.decode())
except ValueError as e:
continue # skip faulty url
if data is not None:
author = data['author_name'].split(' - ')
author = author[0].rstrip()
f = open(output, "a", encoding='utf-8')
print(author, ',', data['title'], sep="", file=f)
It eats a plain text file with Youtube URL list:
https://www.youtube.com/watch?v=F_Vfgdfgg
https://www.youtube.com/watch?v=RndfgdfN8
...
and returns a CSV file with Artist-Title pairs:
Beyonce,Pretty hurts
Justin Timberlake,Cry me a river
There are two modules that can help you which is pafy & youtube-dl. First install this module using pip. Pafy is using youtube-dl in the background to fetch the video information, you can also download videos using pafy and youtube-dl.
pip install youtube_dl
pip install pafy
Now you need to follow this code, I assume that you have the URL of any youtube video.
import pafy
def fetch_yt_video(link):
video = pafy.new(link)
print('Video Title is: ',video.title)
fetch_yt_video('https://youtu.be/CLUsplI4xMU')
The output is
Video Title is: Make the perfect resume | For freshers & experienced | Step by step tutorial with free format

Resources