I have this code, but it doesn't work to showing message and keyboard while using Function Keyboard that I made.
function sendText(id,text) {
var url = telegramUrl + "/sendMessage?chat_id=" + id + "&text=" + text;
var response = UrlFetchApp.fetch(url);
Logger.log(response.getContentText());
}
function Keyboard (id, text, reply_markup ){
var url = telegramUrl + "/sendMessage?chat_id=" + id + "&text=" + text + "&reply_markup=" + reply_markup ;
var response = UrlFetchApp.fetch(url);
Logger.log(response.getContentText());
}
function doPost(e) {
// this is where telegram works
var data = JSON.parse(e.postData.contents);
var text = data.message.text;
var id = data.message.chat.id;
if (text == "/start"){
var message = "Selamat datang. Untuk mencari data pelanggan silahkan memasukkan #ODP_NAME.%0AContoh : #ODP-UBN-FAC/100";
var opts = JSON.stringify({
keyboard: [['OK','Cancel']],
one_time_keyboard: true,
resize_keyboard: true
})
;
//sendText(id, "hola", opts);
Keyboard(id,"hi", opts);
}
}
**and then i try to use Function sendText() like this to make the url true, but it's only give me the text and not showing the keyboard. **
sendText(id,"hi", {reply_markup: JSON.stringify({
keyboard: [['OK','Cancel']],
one_time_keyboard: true,
resize_keyboard: true
})
});
Can you tell me what's wrong with my code?
instead of use get try use post
example :
var keyBoard =JSON.stringify({
"keyboard": [["OK","Cancel"]],
"one_time_keyboard":true,
"resize_keyboard":true
});
var url = "https://api.telegram.org/bot123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11";
function replyKeyboard(){
var formData = {
'chat_id': "1234567",
'text': 'Hello',
'reply_markup': keyBoard
};
var options = {
'method' : 'post',
'payload' : formData
};
UrlFetchApp.fetch(url + "/sendMessage?", options);
}
i think your reply_markup should look like this:
{
keyboard: [[{text: 'OK'}, {text: 'Cancel'}]],
one_time_keyboard: true,
resize_keyboard: true
}
Related
Hello I am trying to implement the share of facebook in my javascript code, however I get this error, I tried several solutions suggested but none was successful in its my implementation.
Could someone help me correct this error?
Thanks in advance. Any help is welcome.
Full code:
https://pastebin.com/kSgFDf0L
Error on console.
FB Share JavaScript "share_button is not defined"
$(document).ready(function() {
window.fbAsyncInit = function() {
FB.init({appId: 'xxxx', status: true, cookie: true,
xfbml: true});
};
(function() {
var e = document.createElement('script'); e.async = true;
e.src = document.location.protocol +
'//connect.facebook.net/en_US/all.js';
document.getElementById('fb-root').appendChild(e);
}());
$(document).ready(function(){
$('#share_button').click(function(e){
e.preventDefault();
FB.ui(
{
method: 'feed',
name: 'This is the content of the "name" field.',
link: 'http://www.groupstudy.in/articlePost.php?id=A_111213073144',
picture: 'http://www.groupstudy.in/img/logo3.jpeg',
caption: 'Top 3 reasons why you should care about your finance',
description: "What happens when you don't take care of your finances? Just look at our country -- you spend irresponsibly, get in debt up to your eyeballs, and stress about how you're going to make ends meet. The difference is that you don't have a glut of taxpayers…",
message: ""
});
});
});
$(".result").on("click", function() {
var id = $(this).attr("data-linkId");
var url = $(this).attr("href");
if(!id) {
alert("data-linkId attribute not found");
}
increaseLinkClicks(id, url);
return false;
});
var grid = $(".imageResults");
grid.on("layoutComplete", function() {
$(".gridItem img").css("visibility", "visible");
});
grid.masonry({
itemSelector: ".gridItem",
columnWidth: 200,
gutter: 5,
isInitLayout: false
});
$("[data-fancybox]").fancybox({
caption : function( instance, item ) {
var caption = $(this).data('caption') || '';
var siteUrl = $(this).data('siteurl') || '';
if ( item.type === 'image' ) {
caption = (caption.length ? caption + '<br />' : '')
+ 'View image<br>'
+ 'Visit page<br>'
+ 'Share';
}
I believe that by declaring the variable it will be possible to execute the function. I just don't know if it will work according to what you expect.
Well. I believe this works ->
caption : function( instance, item ) {
var caption = $(this).data('caption') || '';
var siteUrl = $(this).data('siteurl') || '';
var share_button = $('#share_button') || '';
This is My Pubnub Chat Code
var pubnub = PUBNUB.init({
publish_key : 'my_key',
subscribe_key : 'sub-key'
});
pubnub.subscribe({
channel : "{{$channel}}",
message : function(m){
$(".conversation-list").append(
'<li class="clearfix '+ m.clearifix +' ">' +
'<div class="chat-avatar">' +
'<img src="' + m.image + '">'+
'<i> {{date('h:i')}} </i>' +
'</div>' +
'<div class="conversation-text">' +
'<div class="ctext-wrap">' +
'<i> '+ m.name + '</i>' +
'<p>' + m.message + '</p>' +
'</div>' +
'</div>' +
'</li>'
).animate({scrollTop: $(".conversation-list")[0].scrollHeight}, 0);
$('.reply-text').val('');
},
//connect : publish
});
$('.send-reply-to-user').on('click', function (e) {
e.preventDefault();
if ($('.reply-text').val()== '')
return false;
else
console.log(pubnub.publish);
// console.log(this);
var user_to_id = $(".send-reply-to-user").attr('user_to_id');
var message = $('.reply-text').val();
var name = $('#user_name').val();
var image = document.getElementById("user_image").getAttribute("src");
var clearifix = $('#user_clearifx').val();
pubnub.publish({
channel : "{{$channel}}",
message: { name : name, message : message, image : image, clearifix : clearifix }
});
if ($.trim(message).length != 0) {
$.ajax({
url: '{{route('send:user:chat:message')}}',
cache: false,
method: 'POST',
data: {user_to_id: user_to_id, message: message, _token: '{{csrf_token()}}'},
beforeSend: function () {
},
success: function (result) {
}
})
}
});
This code is Working perfectly only problem is that messages are going to all users, I want to send msg to one to one user.
Example: User one: John send a message to User two Deo,
Example 2: John sends a message to Marry
and so on. Using Pubnub JS API, Backend as Laravel 5.6
I recommend using PubNub's opinionated JavaScript framework called ChatEngine. It takes away a lot of the heavy lifting involved with making chat with PubNub. Here is some example code to get you started making 1:1 private chats. Make sure you use the setup button to prepare the backend on your account.
<script src="https://cdn.jsdelivr.net/npm/chat-engine#0.9.5/dist/chat-engine.min.js" type="text/javascript"></script>
<script type="text/javascript">
// Init ChatEngine with PubNub
const publishKey = '__Your_PubNub_Publish_Key__';
const subscribeKey = '__Your_PubNub_Subscribe_Key__';
const ChatEngine = ChatEngineCore.create({
publishKey,
subscribeKey,
}, {
globalChannel: 'global',
});
const user = {
uuid: 'randomstringofchars',
name: 'John Smith'
}
const chats = {};
ChatEngine.connect(user.uuid, user);
ChatEngine.on('$.ready', function(data) {
// store my new user as `me`
let me = data.me;
// returns a ChatEngine chat object
function makePrivateChat(theirUserId) {
const chatKey = [theirUserId, me.uuid].sort().join('-');
// Don't make the same 1:1 chat if it already exists
if (chats[chatKey]) {
return;
}
// true for private chat
const chat = new ChatEngine.Chat(chatKey, true);
chats[chatKey] = chat;
}
// Auto add a 1:1 chat to UI when invited by someone
me.direct.on('$.invite', makePrivateChat);
// Define a button for making new 1:1 chats in your UI
newOneToOneChatButton.on('click', function (event, theirUserId) {
someChatObject.invite(theirUserId);
});
});
</script>
Finally Fixed My issue, the private Channels working good , Actually problem was with my back-end. It was returning data from all the users i have fixed now its working fine.
I have this API that I'm currently using to output a short URL or URL generator. Is there a way to pass the output to an on-click function.
The first script shows the API running
var base_url = window.location.origin,
hash_bang = "/#/sign-up?referral=",
login = "login",
api_key = "api_key";
function get_short_url(login, api_key, func, value) {
var value = document.getElementById('input-refcode').value;
$.getJSON(
"https://api-ssl.bitly.com//v3/shorten?callback=?",
{
"format": "json",
"apiKey": api_key,
"login": login,
"longUrl": base_url + hash_bang + value
},
function(response)
{
func(response.data.url);
}
);
}
Second is a script that shares a text via Twitter using on-click
$('#twitter').on('click', function() {
win = window.open('https://twitter.com/intent/tweet?text=Get Free Rides at Electric Studio! Sign up to purchase your first timer package! After your first ride, you get 1 ride on us!', '_blank');
win.focus();
});
Is there a way to get the output from the first function get_short_url then bind it in a on-click like this for example
$('#twitter').on('click', get_short_url(login, api_key, function(short_url)) {
win = window.open('https://twitter.com/intent/tweet?text=Get Free Rides at Electric Studio! Sign up to purchase your first timer package! After your first ride, you get 1 ride on us!' + short_url, '_blank');
win.focus();
});
I tried this solution but the browser flagged the function as a pop-up
$('#twitter').on('click', function() {
var base_url = window.location.origin,
hash_bang_twitter = "/%23/sign-up?referral=",
referral_code = document.getElementById('input-refcode').value;
get_short_url(login, api_key, function(short_url) {
win = window.open('https://twitter.com/intent/tweet?text=Get Free Rides at Electric Studio! Sign up ' + short_url + ' to purchase your first timer package! After your first ride, you get 1 ride on us!' + ' https://www.electricstudio.ph/', '_blank');
win.focus();
});
});
There is no need to, you can simply wrap
$('#twitter').on('click', function() {
get_short_url(login, api_key, function(short_url) {
win = ...
win.focus();
});
});
I'm no pro at js, but this seems fairly simple. I have not tested this.
var base_url = window.location.origin,
hash_bang = "/#/sign-up?referral=",
login = "login",
api_key = "api_key";
function get_short_url() {
var value = ('#input-refcode').val();
var result = '';
$.getJSON(
"https://api-ssl.bitly.com//v3/shorten?callback=?",
{
"format": "json",
"apiKey": api_key,
"login": login,
"longUrl": base_url + hash_bang + value
},
function(response)
{
result = response.data.url;
}
);
return result;
};
$('#twitter').on('click', function() {
var short_url = get_short_url(function(short_url)
if (short_url !== '') {
win = window.open('https://twitter.com/intent/tweet?text=' + encodeURI("Get Free Rides at Electric Studio! Sign up to purchase your first timer package! After your first ride, you get 1 ride on us! " + short_url));
win.focus();
}
});
I'm using jquery-bitly-plugin for shorten some URLs and I'm doing in this way:
var opts = {login: myLogin, key: myKey},
bitly = new $.Bitly(opts);
shorten = bitly.shorten(url, {
onSuccess: function (shortUrl) {
console.info(shortUrl); // this works fine
// I got something like http://bit.ly/1DfLzsF
return shortUrl;
},
onError: function (data) {
console.log(data.errorCode, data.errorMessage);
}
});
Then I tried this:
console.log(shorten);
But got Undefined, why? How do I assign the var in order to use in other places?
EDIT: adding extra information around the problem
This info will clarify a bit what I'm trying to do with my question so I have this code which allow to share some content in social networks on click event:
$('.share-item').click(function () {
var href = '',
url = base_url + 'main/show/' + imgUrl.split("/")[2].split(".")[0];
if ($(this).data('category') == 'share-facebook') {
href = 'https://www.facebook.com/sharer/sharer.php?u=' + url;
}
else if ($(this).data('category') == 'share-twitter') {
text = 'SomeText';
via = 'SomeText2';
href = 'http://www.twitter.com/share/?text=' + text + '&via=' + via + '&url=' + url;
}
else if ($(this).data('category') == 'share-mail') {
$('#finalImgModal').attr('src', imgUrl);
$('#image').val(imgUrl);
$('#mailModal').modal('show');
return false;
}
window.open(href, '', 'menubar=no,toolbar=no,resizable=yes,scrollbars=yes,height=600,width=600');
return false;
});
As you may notice url is common to share-facebook and share-twitter. I need to shorten that URL and pass back to the href on each possible choice. For shorten the URL I'm using jquery-bitly-plugin as follow:
var opts = {login: myLogin, key: myKey},
bitly = new $.Bitly(opts);
bitly.shorten(url, {
onSuccess: function (shortUrl) {
console.info(shortUrl); // this works fine I got
// something like http://bit.ly/1DfLzsF
},
onError: function (data) {
console.log(data.errorCode, data.errorMessage);
}
});
How I can use shortUrl in href parameter? Do I need to repeat the code on each condition in order to use execute the action at onSuccess event from shorten() method? How do you deal with this?
To assign to a variable:
var opts = {login: myLogin, key: myKey},
bitly = new $.Bitly(opts);
bitly.shorten(url, {
onSuccess: function (shortUrl) {
shorten = shortUrl;
},
onError: function (data) {
console.log(data.errorCode, data.errorMessage);
}
});
The method shorten doesn't have a return on source code of plugin.
IMPROVED ANSWER
Based on your edite post, this is the correct answer on how to use it the shortUrl:
$('.share-item').click(function () {
var href = '',
url = base_url + 'main/show/' + imgUrl.split("/")[2].split(".")[0],
opts = {login: myLogin, key: myKey},
bitly = new $.Bitly(opts);
bitly.shorten(url, {
onSuccess: function (shortUrl) {
if ($(this).data('category') == 'share-facebook') {
href = 'https://www.facebook.com/sharer/sharer.php?u=' + shortUrl;
} else if ($(this).data('category') == 'share-twitter') {
text = 'SomeText';
via = 'SomeText2';
href = 'http://www.twitter.com/share/?text=' + text + '&via=' + via + '&url=' + shortUrl;
} else if ($(this).data('category') == 'share-mail') {
$('#finalImgModal').attr('src', imgUrl);
$('#image').val(imgUrl);
$('#mailModal').modal('show');
}
if ($(this).data('category') != 'share-mail')
window.open(href, '', 'menubar=no,toolbar=no,resizable=yes,scrollbars=yes,height=600,width=600');
},
onError: function (data) {
console.log(data.errorCode, data.errorMessage);
}
});
return false;
});
As I said in a comment, you need to figure out a future for the shortened URL. This future here is "open a window with this URL". Here is a quick pseudocode:
function openWindow(shortUrl) {
window.open(shortUrl, '', 'menubar=no,toolbar=no,resizable=yes,scrollbars=yes,height=600,width=600');
}
$('.share-item').click(function () {
if ($(this).data('category') == 'share-mail') {
...
return;
}
if (....twitter...) {
href = ...
} else if (....facebook....) {
href = ...
}
bitly.shorten(url, {
onSuccess: openWindow,
onError: function(err) {
...
}
});
}
(I made the openWindow future into a separate function to make it obvious, but it could just as well have been left inline.)
I am trying to explicitly get the system properties from my table but it is not working. I can see that the URL is returning all the data including these fields if I use https://myservice.azure-mobile.net/tables/todoitem?__systemProperties=* but on the code I cannot get it as item.__version or item.version. I have tried adding todoitemtable = WindowsAzure.MobileServiceTable.SystemProperties.All; but no success! I have also looked at http://azure.microsoft.com/en-us/documentation/articles/mobile-services-html-validate-modify-data-server-scripts/ but this is adding a new column instead of using the existing system columns.
$(function() {
var client = new WindowsAzure.MobileServiceClient('https://ib-svc-01.azure-mobile.net/', 'key');
var todoItemTable = client.getTable('todoitem');
// = WindowsAzure.MobileServiceTable.SystemProperties.All;
// Read current data and rebuild UI.
// If you plan to generate complex UIs like this, consider using a JavaScript templating library.
function refreshTodoItems() {
var query = todoItemTable.where({ complete: false });
query.read().then(function(todoItems) {
var listItems = $.map(todoItems, function(item) {
return $('<li>')
.attr('data-todoitem-id', item.id)
.append($('<button class="item-delete">Delete</button>'))
.append($('<input type="checkbox" class="item-complete">').prop('checked', item.complete))
.append($('<div>').append($('<input class="item-text">').val(item.id))
.append($('<span class="timestamp">'
+ (item.createdAt && item.createdAt.toDateString() + ' '
+ item.createdAt.toLocaleTimeString() || '')
+ '</span>')));
});
$('#todo-items').empty().append(listItems).toggle(listItems.length > 0);
$('#summary').html('<strong>' + todoItems.length + '</strong> item(s)');
}, handleError);
}
function handleError(error) {
var text = error + (error.request ? ' - ' + error.request.status : '');
$('#errorlog').append($('<li>').text(text));
}
function getTodoItemId(formElement) {
return $(formElement).closest('li').attr('data-todoitem-id');
}
// Handle insert
$('#add-item').submit(function(evt) {
var textbox = $('#new-item-text'),
itemText = textbox.val();
if (itemText !== '') {
todoItemTable.insert({ text: itemText, complete: false }).then(refreshTodoItems, handleError);
}
textbox.val('').focus();
evt.preventDefault();
});
// Handle update
$(document.body).on('change', '.item-text', function() {
var newText = $(this).val();
todoItemTable.update({ id: getTodoItemId(this), text: newText }).then(null, handleError);
});
$(document.body).on('change', '.item-complete', function() {
var isComplete = $(this).prop('checked');
todoItemTable.update({ id: getTodoItemId(this), complete: isComplete }).then(refreshTodoItems, handleError);
});
// Handle delete
$(document.body).on('click', '.item-delete', function () {
todoItemTable.del({ id: getTodoItemId(this) }).then(refreshTodoItems, handleError);
});
// On initial load, start by fetching the current data
refreshTodoItems();
});
I was trying to access the system properties from within the API scripts and found this and thought it was useful and relevant: http://www.brandonmartinez.com/2014/10/22/retrieve-system-properties-in-azure-mobile-services-javascript-backend/
Basically you can do this (example from the post):
myTable.read({
systemProperties: ['__createdAt', '__updatedAt'],
success: function(tableEntries) {
// So on and so forth
}
}