I am very new to bot development. I am playing wit.ai with facebook messanger. How do we set quick replies from action?
Here is how I do it:
if quick_replies:
data['message']['quick_replies'] =[{'content_type': 'text', 'title': qr, 'payload': 'n/a'} for qr in quick_replies]
requests.post(FB_URL % 'me/messages', json=data, headers={'Content-Type': 'application/json'}).json()
I get the quick_replies list from Wit.ai, when it calls my send action. For example:
def send(request, response):
fb.send_message(request['session_id'][32:], response['text'], response['quickreplies'] if ('quickreplies' in response) else None)
return request['context']
Related
I am new to web-scraping.
I want to go to Webpage_A and follow all the links there.
Each of the link lead to a page where I can select some button and download the data in an Excel file.
I tried the below code. But I believe there is an error with
if link:
yield SeleniumRequest(
Instead of using "SeleniumRequest" to follow the links, what should I use?
If using pure Scrapy, I know I can use
yield response.follow(
Thank you
class testSpider(scrapy.Spider):
name = 'test_s'
def start_requests(self):
yield SeleniumRequest(
url='CONFIDENTIAL',
wait_time=15,
screenshot=True,
callback=self.parse
)
def parse(self, response):
tables_name = response.xpath("//div[#class='contain wrap:l']//li")
for t in tables_name:
name=t.xpath(".//a/span/text()").get()
link = t.xpath(".//a/#href").get()
if link:
yield SeleniumRequest(
meta={'table_name': name},
url= link,
wait_time=15,
screenshot=True,
callback=self.parse_table
)
def parse_table(self, response):
name = response.request.meta['table_name']
button_select=response.find_element_by_xpath("(//a[text()='Select All'])").click()
button_st_yr=response.find_element_by_xpath("//select[#name='ctl00$ContentPlaceHolder1$StartYearDropDownList'] /option[1]").click()
button_end_mth=response.find_element_by_xpath("//select[#name='ctl00$ContentPlaceHolder1$EndMonthDropDownList']/option[text()='Dec']").click()
button_download=response.find_element_by_xpath("//input[#id='ctl00_ContentPlaceHolder1_DownloadButton']").click()
yield{
'table_name': name
}
I got this problem. Why i get this access error and how can i fix it?
Odoo Server Error - Access Error
Sorry, you are not allowed to access
this document. Only users with the following access level are
currently allowed to do that:
Administration/Settings
(Document model: ir.config_parameter) - (Operation: read, User: 21)
Here is my code:
Button submit:
<button string="Confirm" name="button_submit" states="draft" type="object" class="oe_highlight"/>
My python code:
def send_email(self, subject, message_body, email_from, email_to):
template_obj = self.env['mail.mail']
template_data = {
'subject': subject,
'body_html': message_body,
'email_from': email_from,
'email_to': email_to
}
template_id = template_obj.create(template_data)
template_obj.send(template_id)
template_id.send()
#api.multi
def request_recuitment_send_mail(self):
""" Send mail with wizard """
base_url = request.env['ir.config_parameter'].get_param('web.base.url')
base_url += '/web#id=%d&view_type=form&model=%s' % (self.id, self._name)
subject = '''Request recuitment for {}'''.format(self.job_id.name)
message_body = '''
<div style="font-size: medium;">
Dear {},
Please check this link for more information Click here
'''.format(
self.user_id.name,
base_url,
)
email_from = '''HR Recruiment <{}>'''.format(self.approver_id.work_email)
email_to = self.user_id.email
self.send_email(subject, message_body, email_from, email_to)
#api.multi
def button_approve(self):
subject = "Request recruitment for {self.job_id.name} has been approved "
body = '''
Position Request: {}
Quantity of Position: {}
Department: {}
Expected Gross Salary: {}
'''.format(
self.job_id.name,
self.quantity,
self.department_id.name,
self.salary_cross_expected
)
self.env['mail.message'].create({'message_type': "notification",
"subtype": self.env.ref("mail.mt_comment").id,
'body': body,
'subject': subject,
'needaction_partner_ids': [(4, self.user_id.partner_id.id,)],
'model': self._name,
'res_id': self.id,
})
self.request_recuitment_approved_send_mail()
self.write({'state': 'approved'})
It should be safe to use sudo() in this case:
request.env['ir.config_parameter'].sudo().get_param('web.base.url')
"Normal" Users don't have any rights on model ir.config_parameter (System parameters). Only the admin (one of its default access groups) or the superuser can read such parameters.
About sudo([flag=True]) from the current documentation (Odoo 15):
Returns a new version of this recordset with superuser mode enabled or disabled, depending on flag. The superuser mode does not change the current user, and simply bypasses access rights checks.
IMPORTANT: I'm not completely sure when it was changed, but IIRC the "current user change" was removed since Odoo 13. So for Odoo 12 sudo will change the current user, which for example will have impacts on default values on creation, created message authors, and so on.
In your case that's irrelevant, because you're only getting the base url or the parameter value, and that's it.
In my webform controller, I am attempting to assign email addresses entered in a webform to a given record. This is the snippet of code in my controller responsible for that
if 'followers' in request.params:
raw_emails = request.httprequest.form.get('followers').split(',')
emails = [user.strip() for user in raw_emails]
#emails = ['foo#bar.com', 'foo2#bar.com',..]
for email in emails:
follower = request.env['res.users'].search(
[('email', '=', email)])
if bool(follower):
reg = {
'res_id': new_ticket.id,
'res_model': 'helpdesk.ticket',
'partner_id': follower.id
}
request.env['mail.followers'].create(reg)
else:
message = "TO DO: Add {} to the system and make the user a follower of this ticket".format(
email)
new_ticket.message_post(body=message)
With this I get strange results i.e after entering "user A" as a follower on the webform, "user B" gets added as a follower. I'm thinking the problem might be from the wrong user record being loaded into the follower variable but I'm not seeing why. Any feedback would be really appreciated.
You can use the message_subscribe method to add followers to a record set.
def message_subscribe(self, partner_ids=None, channel_ids=None, subtype_ids=None):
""" Main public API to add followers to a record set. Its main purpose is
to perform access rights checks before calling _message_subscribe. """
You have already an example in the account move, in message_new method that add a list of partners.
# Assign followers.
all_followers_ids = set(partner.id for partner in followers + senders + partners if is_internal_partner(partner))
move.message_subscribe(list(all_followers_ids))
I'm searching for some examples to test my drf api with pytest. I made some fixtures to create user and connect. Does someone have a guide/reference to implement a POST test? It is for a product with the following fields: name, description, price and category.
For status_code test I wrote:
#pytest.fixture
def user():
username = 'test'
password = 'test'
User.objects.user(username=username, password=password)
#pytest.fixture
#pytest.mark.django_db
def client(user):
token = Token.objects.get(user__username='test')
client = APIClient()
client.credentials(HTTP_AUTHORIZATION='Token ' + token.key)
return client
#pytest.mark.django_db
def test_status(client):
resp = client.get('/myapi/api/product/')
assert resp.status_code == 200
And it's ok.
For test a product create, I tried this:
#pytest.mark.django_db
def test_create(client):
resp = client.post(
'/myapi/api/product/',
{
'name': 'teste1',
'description': "Teste1",
'price': 3.50,
'category': 1
},
format='json'
)
assert resp.status_code == 201
But I receive 400.
So I have a ouath web app that connects to youtube. I use the youtube analytics calls to get information like number of subscribers from my channel. But right now I try to make a top 10 videos from my channel with the views count for every video included in the response. I use this documentation:
Top videos for subscribed or unsubscribed viewers
My call looks like this:
$command = 'curl -H "Authorization: Bearer ' . $access_token . '" "https://www.googleapis.com/youtube/analytics/v1/reports?ids=channel%3D%3DMINE&start-date=' . date('Y-m-d', strtotime('-31 days')) . '&end-date=' . date('Y-m-d', strtotime('today')). '&metrics=views&dimensions=video&sort=views"';
But I get an error message as a response:
"The query is not supported. Check the documentation at https://developers.google.com/youtube/analytics/v1/available_reports for a list of supported queries."
I also tried this call with YoTube data API:
$videos_url = 'https://www.googleapis.com/youtube/v3/search?part=snippet&forMine=true&order=viewCount&type=video&access_token=' . $access_token;
But it provides this response:
["kind"]=>
string(26) "youtube#searchListResponse"
["etag"]=>
string(57) ""######""
["nextPageToken"]=>
string(112) "#######"
["pageInfo"]=>
object(stdClass)#267 (2) {
["totalResults"]=>
int(1)
["resultsPerPage"]=>
int(5)
}
["items"]=>
array(1) {
[0]=>
object(stdClass)#270 (4) {
["kind"]=>
string(20) "youtube#searchResult"
["etag"]=>
string(57) ""#####""
["id"]=>
object(stdClass)#269 (2) {
["kind"]=>
string(13) "youtube#video"
["videoId"]=>
string(11) "####"
}
["snippet"]=>
object(stdClass)#273 (6) {
["publishedAt"]=>
string(24) "2016-09-14T14:49:49.000Z"
["channelId"]=>
string(24) "#####"
["title"]=>
string(12) "My Slideshow"
["description"]=>
string(87) "I created this video with the YouTube Slideshow Creator (http://www.youtube.com/upload)"
This response provides no views count. I need for every video to get the views count as well.
Any ideas on how to accomplish this? Any help is welcomed! Thank you all for your time!
The issue with your youtube analytics api request is sort parameter. Try using value -views instead of views. You can double check the API link you provided. Also set the max-results
Example URL :
https://www.googleapis.com/youtube/analytics/v1/reports?ids=channel%3D%3Dmine&start-date=2016-05-01&end-date=2016-09-01&metrics=views&dimensions=video&max-results=10&sort=-views&key={YOUR_API_KEY}