I am using Dailymotion python sdk to upload videos to dailymotion. I am unable to set category to 'Education'
Unable to set category to 'Education', works fine if I set it to 'news'.
upload_folder = r"D:\My Folder\Dailymotion\Download_DM\automated_upload"
for file in os.listdir(upload_folder):
try:
d.set_grant_type(
"password",
api_key=_API_KEY,
api_secret=_API_SECRET,
scope=["manage_videos"],
info={"username": _USERNAME, "password": _PASSWORD},
)
# Uploading the file on dailymotion servers
file_path = upload_folder +'\\' + os.path.splitext(file)[0] + ".mp4"
url = d.upload(file_path)
# Filling the information about the video
parameters = {
"url": url,
"title": os.path.splitext(file)[0],
"tags": "life,love,reality,god,spirituality,education,truth,saints,scriptures",
#"description": "my first automatic uplaod",
"published": 1,
"channel": "education"
}
# Sending the information to create the video on dailymotion
result = d.post("/me/videos?fields=id,url", parameters)
print("Uploaded video: ", os.path.splitext(file)[0], "\nDailymotion url: ", result['url'], "\n\n")
except Exception as e:
print("An error occured: %s" % str(e))
Error Message: DailymotionApiError: not_found: Can't find object channel for `channel' parameter
Education is the label of the channel, you have to pass its id which is 'school'.
You can retrieve all the channel ids at this endpoint: https://api.dailymotion.com/channels?fields=id,name
Related
I create a bot to monitor the comment if there is any new comment and if so it will automatically private_replies them But instead i got a Request [400] Error instead.
def monitor_comment():
print("Bot is monitoring comments")
time.sleep(5)
comment_data = graph.get_connections(COMBINED_POST_ID_TO_MONITOR,"comments",order='reverse_chronological')
commends = []
for comment in comment_data['data'][:10]:
commends.append (comment)
data = commends[0]['id']
data_converted = str(data)
#time.sleep(5)
print(data)
return data_converted
def private_reply(comment_ids):
url = "https://graph.facebook.com/v12.0/me/messages?"
access = {"access_token":Page_Token}
params = {
"recipient": {
"comment_id": comment_ids
},
"message": {
"text":"Testing Private_Replies"
}
request = requests.post(url=url, files=access, json=params)
print(request)
This is the logs
{"error":{"message":"An active access token must be used to query information about the current user.","type":"OAuthException","code":2500,"fbtrace_id":"AMCiqy1Aw8CyODPlUBE1b98"}}
I am facing an issue with my web scraping tool.
I have made a fucntion in python to get articles details using SCOPUS search API available on Elsevier dev portal. However, after i run the program it gives me different result set as compare to Elsevier portal.
Elseveir portal- https://www.elsevier.com/
SCOPUS API- https://
api.elsevier.com/content/search/scopus?query=all(gene)&apiKey=7f59af901d2d86f78a
1fd60c1bf9426a
CODE:
url = 'https://api.elsevier.com/content/search/scopus?query=' + query + '&apiKey=' + scp_api
# response object
response = requests.get(url, headers=headers, timeout=30)
soup = BeautifulSoup(response.content, 'lxml')
# convert resonse into josn
obj = json.loads(soup.text)
######## Find required attributes in the response object
for item in obj['search-results']['entry']:
try:
if "prism:Issn" and "prism:issn" not in obj:
issn = item['prism:eIssn']
else:
issn = item['prism:issn']
resp_obj = {"entities": {"Search Engine": "Elsevier SCOPUS Search Engine",
"items": [
{"DOI": item['prism:doi'],
"Title": item['dc:title'],
"URLs": item['prism:url'],
"Authors": item['dc:creator'],
"Publication Name": item['prism:publicationName'],
"ISSN": issn,
"Cited count": item['citedby-count'],
"Affiliation": item['affiliation'][0]['affilname'],
"Type": item['subtypeDescription'],
"Published date": item['prism:coverDate'],
"Abstract": item['prism:publicationName']
}
]}}
# append dict object data
data.append(resp_obj)
except Exception as e: # raise e
pass
# print('error scopus:', e)
Any reasons or help would be appreciated.
Thanks.
I'm trying to filter campaigns based on list id via the API. I'm using the given example at https://mailchimp.com/developer/api/marketing/campaigns/list-campaigns/
However, when I input the parameter, I get the error
TypeError: list() takes 1 positional argument but 2 were given
I am only inputting one parameter.
I tried a few different criteria for the "list" arguement but they all return the same error. Sample code below
import mailchimp_marketing as MailchimpMarketing
from mailchimp_marketing.api_client import ApiClientError
try:
client = MailchimpMarketing.Client()
client.set_config({
"api_key": "xyz",
"server": "xyz"
})
response = client.campaigns.list({"campaigns": [{"recipients": {"list_id": "xyz"}}]})
print(response)
except ApiClientError as error:
print("Error: {}".format(error.text))
import mailchimp_marketing as MailchimpMarketing
from mailchimp_marketing.api_client import ApiClientError
try:
client = MailchimpMarketing.Client()
client.set_config({
"api_key": "xyz",
"server": "xyz"
})
response = client.campaigns.list([{"recipients": {"list_id": "xyz"}}])
print(response)
except ApiClientError as error:
print("Error: {}".format(error.text))
import mailchimp_marketing as MailchimpMarketing
from mailchimp_marketing.api_client import ApiClientError
try:
client = MailchimpMarketing.Client()
client.set_config({
"api_key": "xyz",
"server": "xyz"
})
response = client.campaigns.list({"recipients": {"list_id": "xyz"}})
print(response)
except ApiClientError as error:
print("Error: {}".format(error.text))
import mailchimp_marketing as MailchimpMarketing
from mailchimp_marketing.api_client import ApiClientError
try:
client = MailchimpMarketing.Client()
client.set_config({
"api_key": "xyz",
"server": "xyz"
})
response = client.campaigns.list({"list_id": "xyz"})
print(response)
except ApiClientError as error:
print("Error: {}".format(error.text))
Appreciate any help into this.
Nice to hear from you but I think you're confusing something i.e. you cant get campaigns in Mailchimp by list_id.
For example
response = client.campaigns.list() // This will return all campaigns
response = client.campaigns.get({campaign_id}) // This will return specific campaign
Note: In maximum APIs word list means to get all
And in Mailchimp sdk there is no such method to get campaign using list_id: LINK
And last thing about your error is that message has umpteen causes; the
specific reason here is that all instance methods expect a first arg
which by custom we call self.
I want to access a nested dictionary item from a REST call but I can't figure out how to access it.
Here is the response:
{"deck_id": "z4p8ee99e7wu", "success": true, "cards": [{"suit": "DIAMONDS", "code": "6D", "value": "6", "images": {"png": "https://deckofcardsapi.com/static/img/6D.png", "svg": "https://deckofcardsapi.com/static/img/6D.svg"}, "image": "https://deckofcardsapi.com/static/img/6D.png"}], "remaining": 51}
(I am really interested in the image link)
This is a public REST API, so anyone could run this code.
My goal is to eventually create a card game, but as you can see, I am just a beginner.)
Here is the code:
import requests
import json
response =
requests.get('https://deckofcardsapi.com/api/deck/new/shuffle/?
deck_count=1')
print(response.text)
print(" ")
print("Status code: " + str(response.status_code))
print("Content type: " + response.headers['content-type'])
data = response.json()
print("deck ID: %s" % data["deck_id"])
print("remaining: %s" % data["remaining"])
deckid=data["deck_id"]
remaining=data["remaining"]
card_var =
requests.get('https://deckofcardsapi.com/api/deck/'+deckid+'/draw/?
count=1')
print(card_var.text)
carddata = card_var.json()
Thank you very much for your help.
You can access card image with :
carddata['cards'][0]['image']
what about carddata['cards'][0]['images']?
More specifically, carddata['cards'][0]['images']['svg'], and
carddata['cards'][0]['images']['png'] will return individual formats, svg and png links.
for card in data['cards']:
print 'card code is %s' % card['code']
for ext in card['images']:
print '%s image url is %s' % (ext, card['images'][ext])
I am able to send text to Mattermost channel through incoming webhooks
import requests, json
URL = 'http://chat.something.com/hooks/1pgrmsj88qf5jfjb4eotmgfh5e'
payload = {"channel": "general", "text": "some text"}
r = requests.post(URL, data=json.dumps(payload))
this code simplly post text. I could not find a way to post file to channel. Suppose I want to post file located at /home/alok/Downloads/Screenshot_20170217_221447.png. If anyone know please share.
You can't currently attach files using the Incoming Webhooks API. You would need to use the Mattermost Client API to make a post with files attached to it.
Here's an example of how you could achieve that (using Mattermost API v3 for Mattermost >= 3.5)
SERVER_URL = "http://chat.example.com/"
TEAM_ID = "team_id_goes_here"
CHANNEL_ID = "channel_id_goes_here"
USER_EMAIL = "you#example.com"
USER_PASS = "password123"
FILE_PATH = '/home/user/thing_to_upload.png'
import requests, json, os
# Login
s = requests.Session() # So that the auth cookie gets saved.
s.headers.update({"X-Requested-With": "XMLHttpRequest"}) # To stop Mattermost rejecting our requests as CSRF.
l = s.post(SERVER_URL + 'api/v3/users/login', data = json.dumps({'login_id': USER_EMAIL, 'password': USER_PASS}))
USER_ID = l.json()["id"]
# Upload the File.
form_data = {
"channel_id": ('', CHANNEL_ID),
"client_ids": ('', "id_for_the_file"),
"files": (os.path.basename(FILE_PATH), open(FILE_PATH, 'rb')),
}
r = s.post(SERVER_URL + 'api/v3/teams/' + TEAM_ID + '/files/upload', files=form_data)
FILE_ID = r.json()["file_infos"][0]["id"]
# Create a post and attach the uploaded file to it.
p = s.post(SERVER_URL + 'api/v3/teams/' + TEAM_ID + '/channels/' + CHANNEL_ID + '/posts/create', data = json.dumps({
'user_id': USER_ID,
'channel_id': CHANNEL_ID,
'message': 'Post message goes here',
'file_ids': [FILE_ID,],
'create_at': 0,
'pending_post_id': 'randomstuffogeshere',
}))
I have done a version for API v4, with the use of a personal access token. https://docs.mattermost.com/developer/personal-access-tokens.html
import os
import json
import requests
SERVER_URL = "YOUR_SERVER_URL"
CHANNEL_ID = "YOUR_CHANNEL_ID"
FILE_PATH = './test.jpg'
s = requests.Session()
s.headers.update({"Authorization": "Bearer YOUR_PERSONAL_ACCESS_TOKEN"})
form_data = {
"channel_id": ('', CHANNEL_ID),
"client_ids": ('', "id_for_the_file"),
"files": (os.path.basename(FILE_PATH), open(FILE_PATH, 'rb')),
}
r = s.post(SERVER_URL + '/api/v4/files', files=form_data)
FILE_ID = r.json()["file_infos"][0]["id"]
p = s.post(SERVER_URL + '/api/v4/posts', data=json.dumps({
"channel_id": CHANNEL_ID,
"message": "YOUR_MESSAGE",
"file_ids": [ FILE_ID ]
}))
EDIT:
I have created a simple CLI.
https://github.com/Tim-Schwalbe/python_mattermost
as per #George , you cann't sent the file to the incoming webhook directly.
below is code to send the file to the channel
from mattermostdriver import Driver
team_name = "<name of your team in mattermost>"
channel_name = "<channel name>" # name of channel which you want to upload document
file_path = "<file to uploaded >" # name of the file to upload
message = "<message to sent on channel>"
options = {
"url": "", # url of your mattermost acocunt https://<url>
"port": 8065, # port of the website
"password": "<account password>",
"login_id": "<login id>",
"token": None
}
x = Driver(options=options)
# loggin into the mattermost server
x.login()
# getting team id
team_id = x.teams.get_team_by_name(team_name)['id']
# getting channel id
channel_id = x.channels.get_channel_by_name(team_id, channel_name)['id'] # give channel id
#setting up the options
form_data = {
"channel_id": ('', channel_id),
"client_ids": ('', "id_for_the_file"),
"files": (file_path, open(file_path, 'rb'))
}
pp = x.files.upload_file(channel_id, form_data)
file_id = pp['file_infos'][0]['id']
# uploading the file
x.posts.create_post({'channel_id': channel_id, "message": message, "file_ids": [file_id]})
# logout from the server
x.logout()