-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmessenger-codes
executable file
·226 lines (183 loc) · 6.83 KB
/
messenger-codes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
#!/usr/bin/env node
const axios = require("axios");
const crypto = require("crypto");
const fs = require("fs");
const path = require("path");
const inquirer = require('inquirer');
const program = require('commander');
const git = require('simple-git');
const currentDir = process.cwd();
const repo = git(currentDir);
const isNull = (v) => (v === undefined) || (v === null);
const isNonNull = (v) => !isNull(v);
let cmdValue, envValue, env2Value;
program
.version('0.1.0')
.description('Manage messenger short codes with source control')
.usage(`mcodes provides simple functions to manage Facebook Messenger codes
with a configuration driven CLI allowing you to manage your codes with source
control.
Read More:
https://developers.facebook.com/docs/messenger-platform/discovery/messenger-codes
init [options] <file ...>
Intializes a folder, config file and manifest file for your messenger application
create <ref> <description>
Creates a new messenger code with a ref and description, and places it in the mcodes directory
sync
Commits and syncs your local mcodes to the remote repository`)
.arguments('<cmd> [arg1] [arg2] [arg3]')
.action(function (cmd, arg1, arg2) {
cmdValue = cmd;
envValue = arg1;
env2Value = arg2;
})
.option('-d, --debug', 'Debug')
.option('-f, --force', 'Force')
.option('-a, --auth-token [value]', 'Facebook page auth token')
program.parse(process.argv);
if (typeof cmdValue !== 'undefined') {
switch (cmdValue) {
case 'sync':
console.log('Syncing with git repo...');
syncRepo();
break;
case 'create':
createCodeRequested(envValue, env2Value);
break;
case 'init':
initialize()
break;
default:
break;
}
} else {
console.log( program.helpInformation() );
process.exit(0);
}
async function initialize() {
if (fs.existsSync(path.join(currentDir, 'mcodes.config.json'))) {
console.log('mcodes already initialized');
return;
}
repo.checkIsRepo((err, result) => {
if (isNonNull(err) || result === false) {
console.log('Must be a git repo');
throw err;
} else {
const questions = [
{
type: 'input',
name: 'pageName',
message: "Page Name"
},
{
type: 'input',
name: 'pageAccessToken',
message: "Page Access token"
},
{
type: 'input',
name: 'appId',
message: "App ID"
},
{
type: 'input',
name: 'folder',
message: "folder",
default: 'messenger-codes'
},
];
inquirer.prompt(questions).then(async (answers) => {
const pageName = answers.pageName;
const pageAccessToken = answers.pageAccessToken;
const appId = answers.appId;
const folder = answers.folder;
if (fs.existsSync(answers.folder) === true) {
console.log("Folder already exists.");
} else {
fs.mkdirSync(answers.folder);
}
fs.writeFileSync(path.join(currentDir, 'mcodes.config.json'), JSON.stringify({
name: pageName,
appId,
pageAccessToken,
folder: answers.folder
}, null, "\t"));
fs.mkdirSync(path.join(folder, 'img'));
fs.writeFileSync(path.join(folder, 'manifest.json'), JSON.stringify({}, null, "\t"));
const gitIgnore = path.join(currentDir, '.gitignore');
if (gitIgnore) {
fs.appendFileSync(gitIgnore, '\nmcodes.config.json\n');
} else {
fs.writeFileSync(gitIgnore, 'mcodes.config.json\n')
}
console.log('mcodes initialized');
});
}
})
}
async function createCode(ref, pageAccessToken, imageSize) {
if (isNull(ref) || isNull(pageAccessToken)) {
console.log("ref and pageAccesToken must be defined");
return;
}
const size = imageSize || 2000;
const url = "https://graph.facebook.com/v2.6/me/messenger_codes?access_token=" + pageAccessToken;
const method = "POST";
const id = crypto.randomBytes(4).toString('hex');
const data = {
type: "standard",
data: { ref: id },
image_size: size
};
try {
const response = await axios.post(url, data);
return Object.assign({ id: id }, response.data);
} catch (err) {
throw new Error("There was an error resolving the request to Facebook");
}
}
async function createCodeRequested(ref, description) {
if (isNull(ref) || ref.length === 0 || isNull(description) || description.length === 0) {
console.warn('Bad arguments');
}
const newObjJson = { ref, description };
const questions = [
{
type: 'confirm',
name: 'createCode',
message: `Does this look right? \n${JSON.stringify(newObjJson, null, ' ')}`,
default: false
}
];
inquirer.prompt(questions).then(async (answers) => {
const accessToken = require(path.join(currentDir, 'mcodes.config.json'))['pageAccessToken'] || answers['auth-token'];
const size = 2000;
if (answers.createCode === true) {
result = await createCode(ref, accessToken, size);
await saveCode(result.uri, result.id, ref, description);
await syncRepo();
}
});
}
async function saveCode(uri, id, ref, description) {
if (isNull(uri) || isNull(ref)) {
return;
}
const config = require(path.join(process.cwd(), 'mcodes.config.json'));
const manifest = require(path.join(process.cwd(), config.folder, 'manifest.json'))
const response = await axios.get(uri, { responseType: 'arraybuffer'});
const fileBuffer = new Buffer(response.data, "binary");
fs.writeFileSync(path.join(config.folder, 'img', id + '.png'), fileBuffer);
manifest[id] = { uri, ref, description }
fs.writeFileSync(path.join(config.folder, 'manifest.json'), `${JSON.stringify(manifest, null, "\t")}\n`);
}
async function syncRepo() {
const config = require(path.join(process.cwd(), 'mcodes.config.json'));
const commitMessage = `Automated commit by ${require("os").userInfo().username}`
repo.pull('origin', 'master')
.add([`${config.folder}/img/*`, `${config.folder}/manifest.json`])
.commit(commitMessage)
.push('origin', 'master');
console.log('Sync complete.');
};