├── .dockerignore
├── .env.example
├── .eslintrc.json
├── .gitignore
├── Dockerfile
├── LICENSE
├── Procfile
├── README.md
├── commands
├── about.js
├── answers.js
├── ask.js
├── askgood.js
├── blog.js
├── bug.js
├── closethread.js
├── code.js
├── doc.js
├── done.js
├── error.js
├── eval.js
├── google.js
├── jobs.js
├── latex.js
├── mathelp.js
├── monline.js
├── onramp.js
├── ping.js
├── sonramp.js
├── why.js
└── wrap.js
├── deploy-commands.js
├── docker-compose.yml
├── events
├── autocompleteInteraction.js
├── buttonInteraction.js
├── guildMemberAdd.js
├── interactionCreate.js
├── messageCreate.js
├── ready.js
└── slashInteraction.js
├── img
├── backtick.png
├── backtick_highlight.png
├── bot_logo.png
├── dontask2ask.png
└── error.png
├── inchat_octave
├── bot_runner.m
├── clear.m
├── illegal_phrases
├── load_user_data.m
├── load_user_img.m
├── load_workspace.m
├── print_user_gcf.m
├── save_workspace.m
└── workspaces
│ ├── .gitkeep
│ └── octave-workspace
├── index.js
├── msg
├── about.md
├── ask.md
├── askgood.md
├── blog.md
├── blog_error.md
├── bug.md
├── code.md
├── cody.md
├── cronjobs.md
├── doc.md
├── doc_alt.md
├── doc_error.md
├── error.md
├── global_pin.md
├── greeting.md
├── help.md
├── intro.md
├── jobs.md
├── mathelp.md
├── matlab.md
├── octhelp.md
├── online.md
├── onramp.md
├── reply.md
├── slonramp.md
├── thanks.md
├── twitter.md
├── twitter_error.md
├── why.md
├── youtube.md
└── youtube_error.md
├── package-lock.json
├── package.json
├── src
├── cronjobs.js
├── download.js
├── fetch.js
├── inchat-octave.js
├── latex.js
├── mathworks-docs.js
├── minesweeper.js
├── render.js
├── router.js
├── templates.js
└── why.js
└── storage
└── .gitkeep
/.dockerignore:
--------------------------------------------------------------------------------
1 | node_modules
2 | npm-debug.log
3 | .env
--------------------------------------------------------------------------------
/.env.example:
--------------------------------------------------------------------------------
1 | BOT_ID=
2 | BOT_TOKEN=
3 | GUILD_ID=
4 | NEWS_CHANNEL_ID=
5 | DM_INTRO=
6 | HELP_CHANNEL_IDS=["450928036800364546", "456342124342804481", "456342247189774338", "701876298296983652", "644823196440199179", "601495308140019742", "750745113076170843", "453522391377903636"]
7 | HELP_CHANNEL_NAMES=["matlab-help-1", "matlab-help-2", "matlab-help-3", "matlab-help-4", "help-channel", "simulink-help-1", "simulink-help-2", "botspam"]
8 | SPAM_BAIT_CHANNEL_ID=
9 | YOUTUBE_AUTH_KEY=
10 | TWITTER_BEARER_TOKEN=
11 | MUTE_ROLE_ID=
12 | OWNER_ID=
--------------------------------------------------------------------------------
/.eslintrc.json:
--------------------------------------------------------------------------------
1 | {
2 | "env": {
3 | "node": true,
4 | "commonjs": true,
5 | "es2021": true
6 | },
7 | "extends": "eslint:recommended",
8 | "parserOptions": {
9 | "ecmaVersion": "latest"
10 | },
11 | "rules": {
12 | "indent": [
13 | "error",
14 | 4
15 | ],
16 | "quotes": [
17 | "error",
18 | "single"
19 | ],
20 | "semi": [
21 | "error",
22 | "always"
23 | ]
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # Logs
2 | logs
3 | *.log
4 | npm-debug.log*
5 | yarn-debug.log*
6 | yarn-error.log*
7 |
8 | # Runtime data
9 | pids
10 | *.pid
11 | *.seed
12 | *.pid.lock
13 |
14 | # Directory for instrumented libs generated by jscoverage/JSCover
15 | lib-cov
16 |
17 | # Coverage directory used by tools like istanbul
18 | coverage
19 |
20 | # nyc test coverage
21 | .nyc_output
22 |
23 | # Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files)
24 | .grunt
25 |
26 | # Bower dependency directory (https://bower.io/)
27 | bower_components
28 |
29 | # node-waf configuration
30 | .lock-wscript
31 |
32 | # Compiled binary addons (https://nodejs.org/api/addons.html)
33 | build/Release
34 |
35 | # Dependency directories
36 | node_modules/
37 | jspm_packages/
38 |
39 | # TypeScript v1 declaration files
40 | typings/
41 |
42 | # Optional npm cache directory
43 | .npm
44 |
45 | # Optional eslint cache
46 | .eslintcache
47 |
48 | # Optional REPL history
49 | .node_repl_history
50 |
51 | # Output of 'npm pack'
52 | *.tgz
53 |
54 | # Yarn Integrity file
55 | .yarn-integrity
56 |
57 | # dotenv environment variables file
58 | .env
59 |
60 | # test scrips
61 | testing_scripts/*.m
62 |
63 | # latex image file
64 | img/latex.png
65 |
66 | # Log file
67 | log.txt
68 |
69 | # inchat octave outputs
70 | inchat_octave/bot_out.txt
71 | inchat_octave/user_printout.png
72 | inchat_octave/user_code.m
73 | inchat_octave/workspaces/*.mat
74 | inchat_octave/user_upload.*
75 | inchat_octave/run_scrum.m
76 |
77 | # VScode file
78 | .vscode
79 |
80 | # Storage files
81 | storage/cronjob_data.json
82 |
83 | # next.js build output
84 | .next
85 |
86 | .idea/
87 |
--------------------------------------------------------------------------------
/Dockerfile:
--------------------------------------------------------------------------------
1 | FROM node:20
2 |
3 | # Create app directory
4 | WORKDIR /usr/src/app
5 |
6 | # Install app dependencies
7 | # A wildcard is used to ensure both package.json AND package-lock.json are copied
8 | # where available (npm@5+)
9 | COPY package*.json ./
10 |
11 | RUN npm install
12 | # If you are building your code for production
13 | # RUN npm ci --omit=dev
14 |
15 | # Bundle app source
16 | ADD . .
17 |
18 | EXPOSE 8080
19 | CMD [ "node", "index.js" ]
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 | Provide the unofficial Matlab Discord Channel with commands.
635 | Copyright (C) 2018 SMC
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Matlab-Discord-Bot Copyright (C) 2018 SMC
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/Procfile:
--------------------------------------------------------------------------------
1 | worker: node index.js
2 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Matlab-Discord-Bot
2 |
3 | A bot for searching commands from MathWorks docs within Discord.
4 | Allows for Octave integration through Discord chat when installed on a Linux system.
5 |
6 | See [help.md](https://github.com/matlab-discord/Matlab-Discord-Bot/blob/master/msg/help.md) for all commands or type `!help` in chat.
7 |
8 | ## Installation
9 |
10 | 1. Clone this repository (either to your PC or a host).
11 | 2. Create a new copy of the `.env.example` file and rename it to `.env` in the root directory.
12 | 3. Fill in each one of the environment variables in your new `.env` file.
13 |
14 | - #### Environment Variables
15 | `BOT_TOKEN` - Discord Client Secret token from the [Developer Portal](https://discord.com/developers/applications/) for your bot application.
16 |
17 | `NEWS_CHANNEL_ID` - Discord channel ID for newest MathWorks blog posts and videos. This can be left blank.
18 |
19 | `DM_INTRO` - Set this boolean value to 1 (true) or 0 (false) to control if the bot sends an intro message to new users who join the server.
20 |
21 | `YOUTUBE_AUTH_KEY` - The Youtube authentication key used in the Youtube data api v3 for getting the last youtube video published on the MATLAB channel.
22 |
23 | `TWITTER_BEARER_TOKEN` - Twitter API OAuth 2.0 Bearer authorization token used for tweet pulling
24 |
25 | `OWNER_ID` - The user ID for the owner of the bot (You, probably!) for debugging purposes only.
26 |
27 | `GUILD_ID` - This is the "test" guild which commands are immediately registered to. Due to slash command registration, if the test guild is not listed here it will take about 1 hour for Discord to register the command globally.
28 |
29 | `BOT_ID` - The user ID of the bot. This is listed in the [Developer Portal](https://discord.com/developers/applications/) as "Application ID".
30 |
31 | `HELP_CHANNEL_IDS` - Array containing the help channel IDs for the bot. The `.env.example` currently contains the default Matlab Discord Server IDs but these should be replaced if your setup.
32 |
33 | `HELP_CHANNEL_NAMES`- Array containing the default help channel names. This is so that the bot can set the names back to these values after the channel has been left dormant for a period.
34 |
35 | `SPAM_BAIT_CHANNEL_ID` - Channel ID for spam bait to prevent automatic bot spam messages from sending too many messages in the server.
36 |
37 | `MUTE_ROLE_ID` - Role ID to be added to users that send messages in the spam bait channel to prevent them from sending more messages and spamming the server.
38 |
39 | 4. Install library dependencies with `npm install`.
40 | The following libraries have been used:
41 | * [cheerio](https://github.com/cheeriojs/cheerio)
42 | * [discord.js](https://github.com/discordjs/discord.js/)
43 | * [dotenv](https://github.com/motdotla/dotenv)
44 | * [mustache.js](https://github.com/janl/mustache.js/)
45 | * [request](https://github.com/request/request)
46 | * [request-promise](https://github.com/request/request-promise)
47 |
48 | 5. **Be sure that you are using Node 16.9 or greater.** Start the bot by running the following command.
49 | ```
50 | node index.js
51 | ```
52 |
53 | ## Structure
54 |
55 | - Events such as `interactionCreate`, `messageCreate`, and `ready` are located in `./events`.
56 |
57 | - Slash commands can be created in `./commands` using the format below.
58 | ```js
59 | const { SlashCommandBuilder } = require('@discordjs/builders');
60 |
61 | module.exports = {
62 | data: new SlashCommandBuilder()
63 | .setName('COMMAND_NAME')
64 | .setDescription('COMMAND_DESCRIPTION'),
65 | async execute(client, interaction) {
66 | // Command behavior
67 | },
68 | };
69 | ```
70 |
71 | - The bot responds to commands with rendered messages. The templates for these messages are in the [msg](https://github.com/matlab-discord/Matlab-Discord-Bot/tree/master/msg) directory. These markdown files can be changed to change the messages that the bot sends.
72 |
73 |
--------------------------------------------------------------------------------
/commands/about.js:
--------------------------------------------------------------------------------
1 | const { SlashCommandBuilder } = require('@discordjs/builders');
2 | const { renderInter: render } = require('../src/render');
3 |
4 | module.exports = {
5 | data: new SlashCommandBuilder()
6 | .setName('about')
7 | .setDescription('About me. Get the GitHub repo link.'),
8 | async execute(client, interaction) {
9 | await render(interaction, 'about.md');
10 | },
11 | };
12 |
--------------------------------------------------------------------------------
/commands/answers.js:
--------------------------------------------------------------------------------
1 | const { SlashCommandBuilder } = require('@discordjs/builders');
2 | const { renderInter: render } = require('../src/render');
3 | const { answersAutocomplete, searchAnswers } = require('../src/mathworks-docs');
4 |
5 | module.exports = {
6 | data: new SlashCommandBuilder()
7 | .setName('answers')
8 | .setDescription('Search MATLAB Answers')
9 | .addStringOption((option) => option
10 | .setName('question')
11 | .setDescription('Ask your question')
12 | .setRequired(true)
13 | .setAutocomplete(true)),
14 | async execute(client, interaction) {
15 | let userQuery = interaction.options.getString('question');
16 | // If the user inputted no autocomplete option such that there is no URL provided value,
17 | // then take that input and search the answers query ourselves.
18 | if (!userQuery.startsWith("answers")) {
19 | userQuery = (await searchAnswers(userQuery));
20 | } else {
21 | userQuery = {url: `https://www.mathworks.com/matlabcentral/${userQuery}`};
22 | }
23 |
24 | await render(interaction, 'doc.md', { url: userQuery.url});
25 | },
26 | async autocompleteExecute(client, interaction) {
27 | const defaultChoices = [{
28 | name: 'MATLAB Answers',
29 | value: 'https://www.mathworks.com/matlabcentral/answers/help',
30 | }];
31 |
32 | const focusedValue = interaction.options.getFocused();
33 | if (!focusedValue) {
34 | await interaction.respond(defaultChoices).catch(console.log);
35 | return;
36 | }
37 | const searchResults = await answersAutocomplete(focusedValue);
38 | if (!searchResults.length) {
39 | await interaction.respond(defaultChoices).catch(console.log);
40 | return;
41 | }
42 |
43 | await interaction.respond(searchResults).catch(console.log);
44 | },
45 | };
46 |
--------------------------------------------------------------------------------
/commands/ask.js:
--------------------------------------------------------------------------------
1 | const { SlashCommandBuilder } = require('@discordjs/builders');
2 | const { renderInter: render } = require('../src/render');
3 |
4 | module.exports = {
5 | data: new SlashCommandBuilder()
6 | .setName('ask')
7 | .setDescription('Don\'t ask to ask, just ask.'),
8 | async execute(client, interaction) {
9 | await render(interaction, 'ask.md', {}, {}, true);
10 | },
11 | };
12 |
--------------------------------------------------------------------------------
/commands/askgood.js:
--------------------------------------------------------------------------------
1 | const { SlashCommandBuilder } = require('@discordjs/builders');
2 | const { renderInter: render } = require('../src/render');
3 |
4 | module.exports = {
5 | data: new SlashCommandBuilder()
6 | .setName('askgood')
7 | .setDescription('How to ask a good question'),
8 | async execute(client, interaction) {
9 | await render(interaction, 'askgood.md', { username: interaction.user.displayName }, {}, true);
10 | },
11 | };
12 |
--------------------------------------------------------------------------------
/commands/blog.js:
--------------------------------------------------------------------------------
1 | const { SlashCommandBuilder } = require('@discordjs/builders');
2 | const { getNewestBlogEntry } = require('../src/mathworks-docs');
3 | const { renderInter: render } = require('../src/render');
4 |
5 | module.exports = {
6 | data: new SlashCommandBuilder()
7 | .setName('blog')
8 | .setDescription('Posts latest MathWorks blog entry.'),
9 | async execute(client, interaction) {
10 | getNewestBlogEntry()
11 | .then((result) => {
12 | render(interaction, 'blog.md', { result });
13 | })
14 | .catch((error) => {
15 | if (error) {
16 | render(interaction, 'blog_error.md', { error });
17 | }
18 | });
19 | },
20 | };
21 |
--------------------------------------------------------------------------------
/commands/bug.js:
--------------------------------------------------------------------------------
1 | const { SlashCommandBuilder } = require('@discordjs/builders');
2 | const { renderInter: render } = require('../src/render');
3 |
4 | module.exports = {
5 | data: new SlashCommandBuilder()
6 | .setName('bug')
7 | .setDescription('Fetch MathWorks contact link to report a bug.'),
8 | async execute(client, interaction) {
9 | await render(interaction, 'bug.md');
10 | },
11 | };
12 |
--------------------------------------------------------------------------------
/commands/closethread.js:
--------------------------------------------------------------------------------
1 | const { SlashCommandBuilder } = require('@discordjs/builders');
2 | const { renderInter: render } = require('../src/render');
3 |
4 | module.exports = {
5 | data: new SlashCommandBuilder()
6 | .setName('closethread')
7 | .setDescription('Close a thread in one of the help forums'),
8 | async execute(client, interaction) {
9 | const channel = interaction.channel;
10 |
11 | if (channel.isThread()) {
12 | await interaction.reply('This thread has been marked closed by the bot.');
13 | channel.setArchived(true); // archived
14 |
15 | } else {
16 | await interaction.reply({ content: 'This channel is not a valid channel to use closeThread', ephemeral: true });
17 | }
18 | },
19 | };
--------------------------------------------------------------------------------
/commands/code.js:
--------------------------------------------------------------------------------
1 | const { SlashCommandBuilder } = require('@discordjs/builders');
2 | const { renderInter: render } = require('../src/render');
3 |
4 | module.exports = {
5 | data: new SlashCommandBuilder()
6 | .setName('code')
7 | .setDescription('Instructions on how to format code.'),
8 | async execute(client, interaction) {
9 | await render(interaction, 'code.md', {}, { files: ['./img/backtick.png'] }, true);
10 | },
11 | };
12 |
--------------------------------------------------------------------------------
/commands/doc.js:
--------------------------------------------------------------------------------
1 | const { SlashCommandBuilder } = require('@discordjs/builders');
2 | const { renderInter: render } = require('../src/render');
3 | const { docAutocomplete, searchDocs } = require('../src/mathworks-docs');
4 |
5 | module.exports = {
6 | data: new SlashCommandBuilder()
7 | .setName('doc')
8 | .setDescription('Search Mathworks documentation.')
9 | .addStringOption((option) => option
10 | .setName('query')
11 | .setDescription('Enter the search query')
12 | .setRequired(true)
13 | .setAutocomplete(true)),
14 | async execute(client, interaction) {
15 | let userQuery = interaction.options.getString('query');
16 | // If the user inputted a none autocompleted option so that there is no .html path,
17 | // then take that input and search the docs.
18 | if (!(/.*\.html/.exec(userQuery))) {
19 | userQuery = (await searchDocs(userQuery)).path;
20 | }
21 | const docURL = `https://mathworks.com/help/${userQuery}`;
22 | await render(interaction, 'doc.md', { url: docURL });
23 | },
24 | async autocompleteExecute(client, interaction) {
25 | const defaultChoices = [{
26 | name: 'Getting Started',
27 | value: 'matlab/getting-started-with-matlab.html',
28 | }];
29 |
30 | const focusedValue = interaction.options.getFocused();
31 | if (!focusedValue) {
32 | await interaction.respond(defaultChoices).catch(console.log);
33 | return;
34 | }
35 | const searchResults = await docAutocomplete(focusedValue);
36 | if (!searchResults.length) {
37 | await interaction.respond(defaultChoices).catch(console.log);
38 | return;
39 | }
40 |
41 | await interaction.respond(searchResults).catch(console.log);
42 | },
43 | };
44 |
--------------------------------------------------------------------------------
/commands/done.js:
--------------------------------------------------------------------------------
1 | const { SlashCommandBuilder } = require('@discordjs/builders');
2 |
3 | module.exports = {
4 | data: new SlashCommandBuilder()
5 | .setName('done')
6 | .setDescription('Clear a help channel of its busy status.'),
7 | async execute(client, interaction) {
8 | if (!client.help_channel_ids.includes(interaction.channel.id)) {
9 | await interaction.reply({ content: 'This is not a help channel. Use this command in a help-channel to clear its busy status once a question is complete.', ephemeral: true });
10 | }
11 |
12 | // check if the channel is a help channel first
13 | const chan = interaction.channel;
14 | const chan_ind = client.help_channel_ids.indexOf(chan.id);
15 |
16 | // If the help channel is busy, clear its busy status
17 | clearTimeout(client.help_channel_timers[chan_ind]);
18 | client.help_channel_timers[chan_ind] = null;
19 | chan.setName(client.help_channel_names[chan_ind]);
20 | await interaction.reply({ content: 'Channel cleared of busy status.', ephemeral: true }).catch(console.log);
21 | },
22 | };
--------------------------------------------------------------------------------
/commands/error.js:
--------------------------------------------------------------------------------
1 | const { SlashCommandBuilder } = require('@discordjs/builders');
2 | const { renderInter: render } = require('../src/render');
3 |
4 | module.exports = {
5 | data: new SlashCommandBuilder()
6 | .setName('error')
7 | .setDescription('Matlab error message description'),
8 | async execute(client, interaction) {
9 | await render(interaction, 'error.md', {}, { files: ['./img/error.png'] }, true);
10 | },
11 | };
12 |
--------------------------------------------------------------------------------
/commands/eval.js:
--------------------------------------------------------------------------------
1 | const { SlashCommandBuilder } = require('@discordjs/builders');
2 |
3 | // Define the number of messages the eval call will search back
4 | const MSG_SEARCH_LIM = 10;
5 |
6 | module.exports = {
7 | data: new SlashCommandBuilder()
8 | .setName('eval')
9 | .setDescription('Run the 1st codeblock found in the last 10 messages through MATLAB.'),
10 | async execute(client, interaction) {
11 | const messages = await interaction.channel.messages.fetch({ limit: MSG_SEARCH_LIM}); // +1 because we account for the message that called the eval...
12 | const oldMessages = Array.from(messages.entries(), item => item[1].content);
13 |
14 | const codeSearchRegexp = /\`\`\`(?:matlab)?(?:\nmatlab)?((\w|\s|\S)*)\`\`\`/; // regexp to parse user code between code blocks
15 | const matchedMessage = oldMessages.find( codeMsg => codeMsg.match(codeSearchRegexp) );
16 |
17 | if (!matchedMessage) {
18 | interaction.reply({content: 'Messages don\'t contain a valid code formatting block. (Wrapped in ```)', ephemeral: true});
19 | return;
20 | }
21 |
22 | const codeToRun = matchedMessage.match(codeSearchRegexp)[1];
23 | const run_command = `!run\`\`\`matlab\n${codeToRun}\`\`\``;
24 | await interaction.reply(run_command).catch(console.log);
25 | setTimeout(() => interaction.deleteReply(), 50 );
26 | },
27 | };
28 |
--------------------------------------------------------------------------------
/commands/google.js:
--------------------------------------------------------------------------------
1 | const { SlashCommandBuilder } = require('@discordjs/builders');
2 |
3 | module.exports = {
4 | data: new SlashCommandBuilder()
5 | .setName('google')
6 | .setDescription('LMGTFY the message')
7 | .addStringOption((option) => option
8 | .setName('query')
9 | .setDescription('Enter the search query')
10 | .setRequired(true)),
11 | async execute(client, interaction) {
12 | const query = encodeURIComponent(interaction.options.getString('query'));
13 | interaction.reply(`https://www.google.com/search?q=${query}`);
14 | },
15 | };
16 |
--------------------------------------------------------------------------------
/commands/jobs.js:
--------------------------------------------------------------------------------
1 | const { SlashCommandBuilder } = require('@discordjs/builders');
2 | const { renderInter: render } = require('../src/render');
3 |
4 | module.exports = {
5 | data: new SlashCommandBuilder()
6 | .setName('jobs')
7 | .setDescription('Fetch the MathWorks jobs URL.'),
8 | async execute(client, interaction) {
9 | await render(interaction, 'jobs.md');
10 | },
11 | };
12 |
--------------------------------------------------------------------------------
/commands/latex.js:
--------------------------------------------------------------------------------
1 | const { SlashCommandBuilder } = require('@discordjs/builders');
2 | const latex = require('../src/latex');
3 | const download = require('../src/download');
4 |
5 | module.exports = {
6 | data: new SlashCommandBuilder()
7 | .setName('latex')
8 | .setDescription('Format your input in a LaTeX image.')
9 | .addStringOption((option) => option
10 | .setName('input')
11 | .setDescription('LaTeX to be formatted.')
12 | .setRequired(true)),
13 | async execute(client, interaction) {
14 | const input = interaction.options.getString('input');
15 | latex(input).then((imgUrl) => {
16 | // Download the image from the url (this url is strange, doesn't have an extension ending) then send
17 | download(imgUrl, 'img/latex.png', () => {
18 | interaction.reply({ content: `Input: \`${input}\``, files: ['./img/latex.png'] });
19 | });
20 | }).catch((error) => {
21 | if (error) {
22 | interaction.reply('Could not parse latex.');
23 | }
24 | });
25 | },
26 | };
27 |
--------------------------------------------------------------------------------
/commands/mathelp.js:
--------------------------------------------------------------------------------
1 | const { SlashCommandBuilder } = require('@discordjs/builders');
2 | const { renderInter: render } = require('../src/render');
3 |
4 | module.exports = {
5 | data: new SlashCommandBuilder()
6 | .setName('mathelp')
7 | .setDescription('Instruction for how to utilize MATLAB in chat.'),
8 | async execute(client, interaction) {
9 | await render(interaction, 'mathelp.md');
10 | },
11 | };
12 |
--------------------------------------------------------------------------------
/commands/monline.js:
--------------------------------------------------------------------------------
1 | const { SlashCommandBuilder } = require('@discordjs/builders');
2 | const { renderInter: render } = require('../src/render');
3 |
4 | module.exports = {
5 | data: new SlashCommandBuilder()
6 | .setName('monline')
7 | .setDescription('Fetch the Matlab online link'),
8 | async execute(client, interaction) {
9 | await render(interaction, 'online.md');
10 | },
11 | };
12 |
--------------------------------------------------------------------------------
/commands/onramp.js:
--------------------------------------------------------------------------------
1 | const { SlashCommandBuilder } = require('@discordjs/builders');
2 | const { renderInter: render } = require('../src/render');
3 |
4 | module.exports = {
5 | data: new SlashCommandBuilder()
6 | .setName('onramp')
7 | .setDescription('Matlab onramp'),
8 | async execute(client, interaction) {
9 | await render(interaction, 'onramp.md');
10 | },
11 | };
12 |
--------------------------------------------------------------------------------
/commands/ping.js:
--------------------------------------------------------------------------------
1 | const { SlashCommandBuilder } = require('@discordjs/builders');
2 |
3 | module.exports = {
4 | data: new SlashCommandBuilder()
5 | .setName('ping')
6 | .setDescription('Replies with Pong!'),
7 | async execute(client, interaction) {
8 | await interaction.reply('Pong!');
9 | },
10 | };
11 |
--------------------------------------------------------------------------------
/commands/sonramp.js:
--------------------------------------------------------------------------------
1 | const { SlashCommandBuilder } = require('@discordjs/builders');
2 | const { renderInter: render } = require('../src/render');
3 |
4 | module.exports = {
5 | data: new SlashCommandBuilder()
6 | .setName('sonramp')
7 | .setDescription('Simulink onramp'),
8 | async execute(client, interaction) {
9 | await render(interaction, 'slonramp.md');
10 | },
11 | };
12 |
--------------------------------------------------------------------------------
/commands/why.js:
--------------------------------------------------------------------------------
1 | const { SlashCommandBuilder } = require('@discordjs/builders');
2 | const { renderInter: render } = require('../src/render');
3 | const why = require('../src/why');
4 |
5 | module.exports = {
6 | data: new SlashCommandBuilder()
7 | .setName('why')
8 | .setDescription('Answer to all questions.')
9 | .addStringOption((option) => option
10 | .setName('question')
11 | .setDescription('What do you want to know?')
12 | .setRequired(true)),
13 | async execute(client, interaction) {
14 | const userQuestion = interaction.options.getString('question');
15 | await render(interaction, 'why.md', { question: userQuestion, result: why() });
16 | },
17 | };
18 |
--------------------------------------------------------------------------------
/commands/wrap.js:
--------------------------------------------------------------------------------
1 | const { SlashCommandBuilder } = require('@discordjs/builders');
2 |
3 | // Define the max number of messages that can be searched back through.
4 | const MSG_SEARCH_LIM = 10;
5 |
6 | module.exports = {
7 | data: new SlashCommandBuilder()
8 | .setName('wrap')
9 | .setDescription('Wraps the message sent N messages ago in Matlab backticks ```')
10 | .addNumberOption((option) => option
11 | .setName('n_messages_ago')
12 | .setDescription('Message to be wrapped in ```')
13 | .setRequired(true)
14 | .setMinValue(1)
15 | .setMaxValue(MSG_SEARCH_LIM)),
16 | async execute(client, interaction) {
17 | const nthMessage = interaction.options.getInteger('n_messages_ago');
18 | let messages = await interaction.channel.messages.fetch({ limit: MSG_SEARCH_LIM});
19 | messages = Array.from(messages.entries(), msg => msg[1]);
20 | if (messages[nthMessage - 1].author.bot) {
21 | await interaction.reply({ content: 'You cannot wrap bot sent messages.', ephemeral: true }).catch(console.log);
22 | return;
23 | }
24 |
25 | const messageToBeWrapped = messages[nthMessage - 1].content;
26 | const codeSearchRegexp = /```(?:matlab)?(?:\nmatlab)?((\w|\s|\S)*)```/;
27 | if (codeSearchRegexp.exec(messageToBeWrapped)) {
28 | await interaction.reply({ content: 'That message is already code wrapped.', ephemeral: true }).catch(console.log);
29 | return;
30 | }
31 |
32 | const wrappedMessage = `\`\`\`matlab\n${messageToBeWrapped}\`\`\``;
33 | await interaction.reply(wrappedMessage).catch(console.log);
34 | // await interaction.channel.send(wrappedMessage).catch(console.log);
35 | // await interaction.reply({ content: 'Successfully wrapped.', ephemeral: true }).catch(console.log);
36 | },
37 | };
38 |
--------------------------------------------------------------------------------
/deploy-commands.js:
--------------------------------------------------------------------------------
1 | const fs = require('fs');
2 | const { REST } = require('@discordjs/rest');
3 | const { Routes } = require('discord-api-types/v9');
4 |
5 | const token = process.env.BOT_TOKEN;
6 | const clientId = process.env.BOT_ID;
7 | const guildId = process.env.GUILD_ID;
8 |
9 | const commands = [];
10 | const commandFiles = fs.readdirSync('./commands').filter((file) => file.endsWith('.js'));
11 |
12 | for (const file of commandFiles) {
13 | const command = require(`./commands/${file}`);
14 | try {
15 | // Temporary hacky fix to discord.js issue with min_value and max_value
16 | // Will need to update discord.js in the future to fix this issue.
17 | // TODO: Remove this upon updating discord.js to a version where min_value and max_value are fixed.
18 | if (command.data.name === 'wrap') {
19 | const wrapCommand = {
20 | name: 'wrap',
21 | description: 'Wraps the message sent N messages ago in Matlab backticks ```',
22 | options: [
23 | {
24 | max_value: 10,
25 | min_value: 1,
26 | choices: undefined,
27 | autocomplete: undefined,
28 | type: 4,
29 | name: 'n_messages_ago',
30 | description: 'Message to be wrapped in ```',
31 | required: true
32 | }
33 | ],
34 | default_permission: undefined
35 | };
36 | commands.push(wrapCommand);
37 | continue;
38 | }
39 |
40 | commands.push(command.data.toJSON());
41 |
42 | } catch (error) {
43 | console.log(`Command for ${file} is not properly formatted.`);
44 | }
45 | }
46 |
47 | const rest = new REST({ version: '9' }).setToken(token);
48 |
49 | rest.put(Routes.applicationGuildCommands(clientId, guildId), { body: commands })
50 | .then(() => console.log('Successfully registered application commands.'))
51 | .catch(console.error);
52 |
--------------------------------------------------------------------------------
/docker-compose.yml:
--------------------------------------------------------------------------------
1 | version: '3'
2 | services:
3 | matlab-discord-bot:
4 | image: matlab-discord-bot:1.0.3
5 | build: .
6 | env_file:
7 | - .env
8 |
9 |
--------------------------------------------------------------------------------
/events/autocompleteInteraction.js:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | async autocompleteExecute(client, interaction) {
3 | const command = client.commands.get(interaction.commandName);
4 |
5 | if (!command) return;
6 |
7 | try {
8 | await command.autocompleteExecute(client, interaction);
9 | } catch (error) {
10 | console.error(error);
11 | }
12 | },
13 | };
14 |
--------------------------------------------------------------------------------
/events/buttonInteraction.js:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | async buttonExecute(client, interaction) {
3 |
4 | },
5 | };
6 |
--------------------------------------------------------------------------------
/events/guildMemberAdd.js:
--------------------------------------------------------------------------------
1 | const mustache = require('mustache');
2 | const templates = require('../src/templates');
3 |
4 | module.exports = {
5 | name: 'guildMemberAdd',
6 | async execute(client, member) {
7 | if (['true', '1'].includes(process.env.DM_INTRO.toLowerCase())) {
8 | member.send(mustache.render(templates['intro.md'], {}));
9 | }
10 | },
11 | };
12 |
--------------------------------------------------------------------------------
/events/interactionCreate.js:
--------------------------------------------------------------------------------
1 | const { buttonExecute } = require('./buttonInteraction');
2 | const { autocompleteExecute } = require('./autocompleteInteraction');
3 | const { slashExecute } = require('./slashInteraction');
4 |
5 | module.exports = {
6 | name: 'interactionCreate',
7 | async execute(client, interaction) {
8 | // Route each interaction type to the proper interaction behavior
9 |
10 | // Slash command interaction
11 | if (interaction.isCommand()) {
12 | await slashExecute(client, interaction);
13 | }
14 |
15 | if (interaction.isAutocomplete()) {
16 | await autocompleteExecute(client, interaction);
17 | }
18 |
19 | if (interaction.isButton()) {
20 | await buttonExecute(client, interaction);
21 | }
22 |
23 | // if (interaction.isContextMenu()) {
24 | //
25 | // }
26 | //
27 | // if (interaction.isSelectMenu()) {
28 | //
29 | // }
30 | },
31 | };
32 |
--------------------------------------------------------------------------------
/events/messageCreate.js:
--------------------------------------------------------------------------------
1 | const mustache = require('mustache');
2 | const fs = require('fs');
3 | const templates = require('../src/templates');
4 | const router = require('../src/router');
5 |
6 | async function updateHelpChannels(client, channel) {
7 | const chan_ind = client.help_channel_ids.indexOf(channel.id);
8 |
9 | if (client.help_channel_timers[chan_ind] == null) {
10 | const busy_chan_str = `${client.help_channel_names[chan_ind]}-busy`;
11 | channel.setName(busy_chan_str).then((newChannel) => console.log(`Changing help channel to busy, ${newChannel.name}`)).catch(console.error);
12 | client.help_channel_timers[chan_ind] = setTimeout(() => {
13 | console.log(`Changing help channel back to ${client.help_channel_names[chan_ind]}`);
14 | channel.setName(client.help_channel_names[chan_ind]);
15 | client.help_channel_timers[chan_ind] = null;
16 | }, 300000);
17 | } else {
18 | // This channel has a timer established already. Clear it, then reset it
19 | clearTimeout(client.help_channel_timers[chan_ind]);
20 | client.help_channel_timers[chan_ind] = setTimeout(() => {
21 | console.log(`Changing help channel back to ${client.help_channel_names[chan_ind]}`);
22 | channel.setName(client.help_channel_names[chan_ind]);
23 | client.help_channel_timers[chan_ind] = null;
24 | }, 300000);
25 | }
26 | }
27 |
28 | async function logBotDMs(msg) {
29 | // Write message to log file. appends new line
30 | const writeLog = function (logMsg, logType) {
31 | // Open a write stream for the log file. Append to the end
32 | const logStream = fs.createWriteStream('log.txt', { flags: 'a' });
33 | const theDate = new Date();
34 | try { // Try to write the log
35 | logStream.write(`${theDate.toLocaleString()}: ${logType} - ${logMsg}\n`);
36 | } catch (error) {
37 | console.log(error);
38 | logStream.write(`Error writing log... ${error}\n`);
39 | }
40 | // End the log
41 | logStream.end();
42 | };
43 |
44 | writeLog(`[${msg.author.id}, ${msg.author.username}]: ${msg.content}`, 'DM');
45 | }
46 |
47 | async function regexCommandRouting(client, msg) {
48 | let tokens;
49 | let commandExecuted = false;
50 |
51 | for (const route of router) {
52 | if ((tokens = route.regexp.exec(msg.content)) !== null) {
53 | route.use(msg, tokens, client);
54 | commandExecuted = true;
55 | break;
56 | }
57 | }
58 |
59 | return commandExecuted;
60 | }
61 |
62 | async function botMention(msg) {
63 | if (/(thank|thx)/.exec(msg.content)) {
64 | msg.reply(mustache.render(templates['thanks.md']));
65 | } else if (/(hi|hello|good|sup|what's up)/.exec(msg.content)) {
66 | msg.reply(mustache.render(templates['greeting.md']));
67 | } else {
68 | msg.reply(mustache.render(templates['reply.md']));
69 | }
70 | }
71 |
72 | async function goodBot(msg) {
73 | if (/clowns?/.exec(msg.content) !== null) {
74 | await msg.react('🤡');
75 | }
76 | }
77 |
78 | async function spamBait(msg) {
79 | if (msg.channelId === process.env.SPAM_BAIT_CHANNEL_ID) {
80 | const muteRole = msg.member.guild.roles.cache.find(role => role.id === process.env.MUTE_ROLE_ID);
81 | if (!muteRole) {
82 | console.error('Cannot find Mute role');
83 | }
84 | msg.member.roles.add(muteRole);
85 | }
86 | }
87 |
88 | module.exports = {
89 | name: 'messageCreate',
90 | async execute(client, msg) {
91 | if (msg.author.bot) {
92 | return;
93 | }
94 |
95 | // Good bot.
96 | await goodBot(msg);
97 |
98 | // Mute bot spam bait messages
99 | await spamBait(msg);
100 |
101 | // An empty guild indicates this is a private message. Log it
102 | if (!msg.inGuild()) {
103 | await logBotDMs(msg);
104 | }
105 |
106 | const commandExecuted = await regexCommandRouting(client, msg);
107 |
108 | if ((!commandExecuted) && msg.mentions.users.has(client.user.id)) {
109 | await botMention(msg);
110 | }
111 |
112 | if ((!commandExecuted) && client.help_channel_ids.includes(msg.channel.id)) {
113 | await updateHelpChannels(client, msg.channel);
114 | }
115 | },
116 | };
117 |
--------------------------------------------------------------------------------
/events/ready.js:
--------------------------------------------------------------------------------
1 | const icoct = require('../src/inchat-octave');
2 |
3 | module.exports = {
4 | name: 'ready',
5 | once: true,
6 | execute(client) {
7 | // Clear out octave workspaces on startup. Fresh start!
8 | icoct.clearWorkspaces();
9 |
10 | console.log(`Ready! Logged in as ${client.user.tag}`);
11 |
12 | //client.user.setActivity('MATLAB 2021b', { type: 'PLAYING' });
13 | client.user.setActivity('Now with slash commands!', { type: 'PLAYING' });
14 | },
15 | };
16 |
--------------------------------------------------------------------------------
/events/slashInteraction.js:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | async slashExecute(client, interaction) {
3 | const command = client.commands.get(interaction.commandName);
4 |
5 | if (!command) return;
6 |
7 | try {
8 | await command.execute(client, interaction);
9 | } catch (error) {
10 | console.error(error);
11 | return interaction.reply({
12 | content: 'There was an error while executing this command!',
13 | ephemeral: true,
14 | });
15 | }
16 | },
17 | };
18 |
--------------------------------------------------------------------------------
/img/backtick.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/matlab-discord/Matlab-Discord-Bot/def92d900a112d08be6959a19b34631a852d0726/img/backtick.png
--------------------------------------------------------------------------------
/img/backtick_highlight.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/matlab-discord/Matlab-Discord-Bot/def92d900a112d08be6959a19b34631a852d0726/img/backtick_highlight.png
--------------------------------------------------------------------------------
/img/bot_logo.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/matlab-discord/Matlab-Discord-Bot/def92d900a112d08be6959a19b34631a852d0726/img/bot_logo.png
--------------------------------------------------------------------------------
/img/dontask2ask.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/matlab-discord/Matlab-Discord-Bot/def92d900a112d08be6959a19b34631a852d0726/img/dontask2ask.png
--------------------------------------------------------------------------------
/img/error.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/matlab-discord/Matlab-Discord-Bot/def92d900a112d08be6959a19b34631a852d0726/img/error.png
--------------------------------------------------------------------------------
/inchat_octave/bot_runner.m:
--------------------------------------------------------------------------------
1 | function bot_runner(out_file, user_work_file)
2 |
3 | % Inputs
4 | % out_file -- full file path to the output diary text file
5 | % user_work_fille -- full file path to the users .mat workspace
6 |
7 | % Clear the diary if it exists already
8 | if exist(out_file, 'file')
9 | delete(out_file);
10 | end
11 |
12 | % start diary and try user code
13 | diary(out_file);
14 | try
15 | % Load the workspace file if it exists
16 | if(exist(user_work_file, 'file'))
17 | load_workspace;
18 | end
19 | % Run the users code. Stored as a script file
20 | user_code;
21 | % Record the users graphic handle
22 | usergcf = hdl2struct(gcf);
23 | % Save their data to a workspace
24 | save_workspace;
25 | catch e % caught an error. display the error
26 | disp(e.message);
27 | end
28 |
29 | % Turn off the diary
30 | diary('off');
31 |
32 | % Check if anything was written to the diary. Put a default message if not
33 | file_obj = dir(out_file);
34 | if(file_obj.bytes == 0)
35 | diary(out_file);
36 | disp('Command executed');
37 | diary('off');
38 | end
39 |
40 | end
--------------------------------------------------------------------------------
/inchat_octave/clear.m:
--------------------------------------------------------------------------------
1 | % Shadow function used so we don't clear out necessary variables for the bot to operate
2 | builtin('clear', '-x', 'out_file', 'user_work_file');
--------------------------------------------------------------------------------
/inchat_octave/illegal_phrases:
--------------------------------------------------------------------------------
1 | dos
2 | (?:[^fs]|^)print
3 | dbcont
4 | ls
5 | system
6 | str2func
7 | eval
8 | feval
9 | cd
10 | rmdir
11 | delete
12 | unix
13 | keyboard
14 | dbstop
15 | input
16 | open
17 | perl
18 | python
19 | popen\d?
20 | pclose
21 | fclose
22 | fopen
23 | waitpid
24 | fork
25 | exec
26 | EXEC_PATH
27 | pipe
28 | dup2
29 | fcntl
30 | kill
31 | dir
32 | ls_command
33 | pwd
34 | setenv
35 | putenv
36 | unsetenv
37 | get_home_directory
38 | getenv
39 | movefile
40 | rename
41 | copyfile
42 | unlink
43 | link
44 | symlink
45 | readlink
46 | mkdir
47 | confirm_recursive_rmdir
48 | mkfifo
49 | unmask
50 | \w?stat
51 | fileattrib
52 | isdir
53 | readdir
54 | file_in_path
55 | \w*zip\d?
56 | \w*tar
57 | unpack
58 | uname/g
59 | fclose
60 | feof
61 | ferror
62 | fget\w
63 | fileread
64 | frewind
65 | fscanf
66 | fseek
67 | ftell
68 | fwrite
69 | importdata
70 | imread
71 | (?:[^up]|^)load
72 | readcell
73 | readmatrix
74 | readtable
75 | readvars
76 | save
77 | textscan
78 | read\w*
79 | usejava
--------------------------------------------------------------------------------
/inchat_octave/load_user_data.m:
--------------------------------------------------------------------------------
1 | function load_user_data(user_work_file, data_file)
2 |
3 | % Load the data file, then save the workspace
4 | try
5 | % Load the workspace file if it exists
6 | if(exist(user_work_file, 'file'))
7 | load_workspace;
8 | end
9 | load(data_file);
10 | builtin('clear', 'data_file');
11 | save_workspace;
12 | catch e
13 | disp e
14 | end
15 |
16 | end
17 |
--------------------------------------------------------------------------------
/inchat_octave/load_user_img.m:
--------------------------------------------------------------------------------
1 | function load_user_img(user_work_file, image_file)
2 |
3 | try
4 | % Load the workspace file if it exists
5 | if(exist(user_work_file, 'file'))
6 | load_workspace;
7 | end
8 |
9 | % Save the users uploaded image as variable `img`, then save the workspace
10 | img = imread(image_file);
11 | save_workspace;
12 | catch e
13 | disp e
14 | end
15 |
16 | end
--------------------------------------------------------------------------------
/inchat_octave/load_workspace.m:
--------------------------------------------------------------------------------
1 | % Script that handles the binary option needed when saving.
2 | % assumes there is a variable called `user_work_file` in the workspace that points to the save location
3 | load('-v7', user_work_file)
4 |
--------------------------------------------------------------------------------
/inchat_octave/print_user_gcf.m:
--------------------------------------------------------------------------------
1 | function print_user_gcf(user_work_file, printout_file)
2 |
3 | % Load the workspace file if it exists
4 | if(exist(user_work_file, 'file'))
5 | load_workspace;
6 | else
7 | % Just return if they dont have the work file already made...
8 | error('Can''t find user work space');
9 | return;
10 | end
11 |
12 | % Check if the user has a gcf in their workspace. print it if so
13 | if exist('usergcf', 'var')
14 | hand = struct2hdl(usergcf);
15 | saveas(hand, printout_file);
16 | else
17 | error('User doesn''t have a saved graphics handle.');
18 |
19 | end
20 |
21 | end
--------------------------------------------------------------------------------
/inchat_octave/save_workspace.m:
--------------------------------------------------------------------------------
1 | % Script that handles the binary option needed when saving.
2 | % assumes there is a variable called `user_work_file` in the workspace that points to the save location
3 | save('-mat7-binary', user_work_file)
4 | %'^(?!(user_work_file)$).'
--------------------------------------------------------------------------------
/inchat_octave/workspaces/.gitkeep:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/matlab-discord/Matlab-Discord-Bot/def92d900a112d08be6959a19b34631a852d0726/inchat_octave/workspaces/.gitkeep
--------------------------------------------------------------------------------
/inchat_octave/workspaces/octave-workspace:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/matlab-discord/Matlab-Discord-Bot/def92d900a112d08be6959a19b34631a852d0726/inchat_octave/workspaces/octave-workspace
--------------------------------------------------------------------------------
/index.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 | require('dotenv').config();
3 | const fs = require('fs');
4 | const { Client, Collection, Intents } = require('discord.js');
5 | const { initCronJobs } = require('./src/cronjobs');
6 | require('./deploy-commands');
7 |
8 | /*
9 | Set bot intents.
10 | */
11 | const myIntents = new Intents();
12 | myIntents.add(Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES, Intents.FLAGS.DIRECT_MESSAGES);
13 |
14 | const client = new Client({ partials: ['CHANNEL'], intents: myIntents });
15 |
16 | /*
17 | Import in bot commands
18 | */
19 | client.commands = new Collection();
20 | const commandFiles = fs.readdirSync('./commands').filter((file) => file.endsWith('.js'));
21 |
22 | for (const file of commandFiles) {
23 | const command = require(`./commands/${file}`);
24 | client.commands.set(command.data.name, command);
25 | }
26 |
27 | /*
28 | Import in bot events
29 | */
30 | const eventFiles = fs.readdirSync('./events').filter((file) => file.endsWith('.js'));
31 |
32 | for (const file of eventFiles) {
33 | const event = require(`./events/${file}`);
34 | if (event.once) {
35 | client.once(event.name, (...args) => event.execute(client, ...args));
36 | } else {
37 | client.on(event.name, async (...args) => await event.execute(client, ...args));
38 | }
39 | }
40 |
41 | /*
42 | Save bot channel ids
43 | */
44 | client.help_channel_ids = JSON.parse(process.env.HELP_CHANNEL_IDS);
45 | client.help_channel_names = JSON.parse(process.env.HELP_CHANNEL_NAMES);
46 | client.help_channel_timers = Array(client.help_channel_ids.length).fill(null);
47 |
48 | const clientCronJobs = () => initCronJobs(client);
49 |
50 | client.login(process.env.BOT_TOKEN).then(clientCronJobs);
51 |
--------------------------------------------------------------------------------
/msg/about.md:
--------------------------------------------------------------------------------
1 | I am open-source. You can fix me at
2 |
3 |
--------------------------------------------------------------------------------
/msg/ask.md:
--------------------------------------------------------------------------------
1 | You may ask your question in one of the help channels. **Asking if there is someone available to help is unnecessary**. Post your question, providing as much detail as necessary along with whatever code you have written so far.
2 |
3 | https://dontasktoask.com/
--------------------------------------------------------------------------------
/msg/askgood.md:
--------------------------------------------------------------------------------
1 | To maximise the chances of getting your question answered, you need to structure it in a way that makes it easy for people to help.
2 |
3 | 1) Post your question with as much detail as possible.
4 | 2) Share code you have written so far.
5 | 3) If you're getting an error message, share the error message.
6 | 4) Bonus points if you share the link you've tried to understand after googling "matlab + your question".
7 |
--------------------------------------------------------------------------------
/msg/blog.md:
--------------------------------------------------------------------------------
1 | {{{result.url}}}
--------------------------------------------------------------------------------
/msg/blog_error.md:
--------------------------------------------------------------------------------
1 | Error: Could not fetch newest blog entry.
--------------------------------------------------------------------------------
/msg/bug.md:
--------------------------------------------------------------------------------
1 | Try contacting technical support!
2 |
3 | https://www.mathworks.com/support/contact_us.html
--------------------------------------------------------------------------------
/msg/code.md:
--------------------------------------------------------------------------------
1 | Wrap your code in three backticks to post code into Discord chat. Activate syntax highlighting for MATLAB code by adding "matlab" after the first three backticks.
2 |
3 | \`\`\`matlab
4 | foobar = [1:10]; %comment
5 | \`\`\`
6 |
7 | The example above results in:
8 | ```matlab
9 | foobar = [1:10]; %comment
10 | ```
11 | For longer code paste your `.m` and `.mat` files directly into chat or use .
12 |
--------------------------------------------------------------------------------
/msg/cody.md:
--------------------------------------------------------------------------------
1 | Looking for a few more challenges after the onramp? Try your hand at the MATLAB Cody challenges:
2 | https://www.mathworks.com/matlabcentral/cody/
--------------------------------------------------------------------------------
/msg/cronjobs.md:
--------------------------------------------------------------------------------
1 | Cronjobs looking for MathWorks updates:
2 | ```
3 | {{{result}}}
4 | ```
5 |
--------------------------------------------------------------------------------
/msg/doc.md:
--------------------------------------------------------------------------------
1 | {{{url}}}
--------------------------------------------------------------------------------
/msg/doc_alt.md:
--------------------------------------------------------------------------------
1 | {{{result.title}}}{{{toolbox}}}: ```
2 | {{{result.summary}}}
3 | ```<{{{result.url}}}>
--------------------------------------------------------------------------------
/msg/doc_error.md:
--------------------------------------------------------------------------------
1 | No results for: {{{query}}}
--------------------------------------------------------------------------------
/msg/error.md:
--------------------------------------------------------------------------------
1 | ## Error Messages
2 | Error messages provide information about crashes and can help to identify their root cause. The **top** lines show the actual error message, and often suggest how to fix it.
3 | ### How to use the error message
4 | 1. Read the error message to understand the type of mistake. Google the message if it doesn't make sense.
5 | 2. Use the hyperlinks in the error message to isolate problem areas.
6 | 3. Identify and correct the issue. Use pause-on-errors and the debugger to find issues and to test your fix
7 | *Trying* to fix your own problem is a great way to learn the language, but if you're still stuck, **ask for help**.
--------------------------------------------------------------------------------
/msg/global_pin.md:
--------------------------------------------------------------------------------
1 | From {{{msg.author}}} in {{{msg.channel}}}:
2 | ==
3 | {{{msg.content}}}
--------------------------------------------------------------------------------
/msg/greeting.md:
--------------------------------------------------------------------------------
1 | Hello. Let us program some Matlab.
--------------------------------------------------------------------------------
/msg/help.md:
--------------------------------------------------------------------------------
1 | **Commands:**
2 | ```
3 | !mathelp: Instruction for how to utilize MATLAB in chat.
4 |
5 | !`` : Renders a LaTeX image with supplied message.
6 |
7 | !about : About me. Get the GitHub repo link.
8 |
9 | !bug : Fetch MathWorks contact link to report a bug.
10 |
11 | !code : Reminder on how to paste code into Discord chat.
12 |
13 | !doc : Search for in the Mathworks docs. (m)
14 |
15 | !done : Clear a help channel of its busy status. (exit, answered, close)
16 |
17 | !eval : Run code through MATLAB found in a codeblock within the last 5 messages. (evaluate)
18 |
19 | !google : lmgtfy the last message sent, or the supplied.
20 |
21 | !help : Display this help message!
22 |
23 | !intro : Post the intro that is DM'd to new users when joining the server for the first time.
24 |
25 | !jobs : Fetch the MathWorks jobs URL.
26 |
27 | !online : Fetch the MATLAB online link.
28 |
29 | !onramp : Display the MATLAB onramp message suggestion and fetch link.
30 |
31 | !rand : Return a random number between 1 and , 6 by default. (roll)
32 |
33 | !octhelp : Instructions for how to utilize Octave in chat.
34 |
35 | !slonramp : Display the Simulink onramp message suggestion and fetch link.
36 |
37 | !why : Answer to all questions.
38 | ```
39 |
--------------------------------------------------------------------------------
/msg/intro.md:
--------------------------------------------------------------------------------
1 | **Welcome to the Matlab Discord Server!**
2 |
3 | If you are new to Matlab, check out the official Matlab tutorials:
4 |
5 |
6 | MathWorks offers an onramp course that we highly recommend as well:
7 |
8 |
9 | __**Asking For Help**__
10 | Most questions can be answered by googling "matlab + your question".
11 |
12 | If you still need help, ask your question fully outright in any relevant channel labeled `help` that is not busy. Be sure to provide all relevant code and material when asking.
13 |
14 | **Do not ping other users for help.** People who want and are willing to help will read the chat.
15 |
16 | __**Bot Commands**__
17 | Use bot commands in <#453522391377903636>. Write `!help` in chat to get a list of all commands.
18 |
19 | __**Posting Code in Chat**__
20 | When posting code in chat, wrap your code in three *backticks* and add *matlab* after the first three for syntax highlighting. For example typing:
21 |
22 | \`\`\`matlab
23 | foobar = [1:10]; %comment
24 | \`\`\`
25 |
26 | Results in:
27 | ```matlab
28 | foobar = [1:10]; %comment
29 | ```
--------------------------------------------------------------------------------
/msg/jobs.md:
--------------------------------------------------------------------------------
1 | We're hiring!
2 | Take a look at some of the job opportunities available online.
3 | https://www.mathworks.com/company/jobs/opportunities.html
4 |
--------------------------------------------------------------------------------
/msg/mathelp.md:
--------------------------------------------------------------------------------
1 | **This bot has the ability to process MATLAB code in Discord, posting console outputs to the chat.**
2 | > • Certain functions and operations have been restricted to work properly with discord.
3 | > • Each user has their own individual workspace, allowing you to save variables.
4 |
5 | *Octave code is also able to be processed in chat. See `!octhelp` for more instructions*
6 |
7 | **Related Functions:**
8 | ```
9 | !run : Execute code and post console output to channel.
10 |
11 | !print : Print current graphic figure to channel. The figure printed is associated with the last graphic figure generated among all users.
12 | ```
13 |
14 | **Example use of in-chat MATLAB, type your commands as followed.**
15 | > !run\`\`\`matlab
16 | > foobar = 1:10; % my command
17 | > disp(foobar);
18 | > \`\`\`
19 |
20 | **This will create a formatted message that the bot can understand and execute.**
21 | > !run```matlab
22 | > foobar = 1:10; % my command
23 | > disp(foobar);
24 | > ```
--------------------------------------------------------------------------------
/msg/matlab.md:
--------------------------------------------------------------------------------
1 | Matlab is a matrix-based language that is the world's most natural way to express computational mathematics.
2 |
--------------------------------------------------------------------------------
/msg/octhelp.md:
--------------------------------------------------------------------------------
1 | **This bot has the ability to process Octave code in Discord, posting console outputs to the chat.**
2 | > • Certain functions and operations have been restricted to work properly with discord.
3 | > • Each user has their own individual workspace, allowing you to save figures and variables.
4 |
5 | **Related Functions:**
6 | ```
7 | !oct : Execute code and post console output to channel. (orun, octave)
8 |
9 | !opr : Print users graphic figure to channel. (oprint, octaveprint)
10 |
11 | !oup : Upload attached image file to users workspace. (oupload, octaveupload)
12 | ```
13 |
14 | **Example use of in-chat Octave, type your commands as followed.**
15 | > !oct\`\`\`matlab
16 | > foobar = 1:10; % my command
17 | > disp(foobar);
18 | > \`\`\`
19 |
20 | **This will create a formatted message that the bot can understand and execute.**
21 | > !oct```matlab
22 | > foobar = 1:10; % my command
23 | > disp(foobar);
24 | > ```
--------------------------------------------------------------------------------
/msg/online.md:
--------------------------------------------------------------------------------
1 | https://matlab.mathworks.com/
--------------------------------------------------------------------------------
/msg/onramp.md:
--------------------------------------------------------------------------------
1 | We recommend all new users take the MATLAB Onramp course to become familiarized with MATLAB.
2 | https://www.mathworks.com/learn/tutorials/matlab-onramp.html
3 |
--------------------------------------------------------------------------------
/msg/reply.md:
--------------------------------------------------------------------------------
1 | Same.
--------------------------------------------------------------------------------
/msg/slonramp.md:
--------------------------------------------------------------------------------
1 | We recommend all new users take the Simulink Onramp course to become familiarized with Simulink.
2 | https://www.mathworks.com/learn/tutorials/simulink-onramp.html
3 |
--------------------------------------------------------------------------------
/msg/thanks.md:
--------------------------------------------------------------------------------
1 | Always a pleasure.
--------------------------------------------------------------------------------
/msg/twitter.md:
--------------------------------------------------------------------------------
1 | {{{result.url}}}
--------------------------------------------------------------------------------
/msg/twitter_error.md:
--------------------------------------------------------------------------------
1 | Could not fetch tweets.
--------------------------------------------------------------------------------
/msg/why.md:
--------------------------------------------------------------------------------
1 | Question: Why {{{question}}}?
2 | Answer: {{{result}}}
3 |
--------------------------------------------------------------------------------
/msg/youtube.md:
--------------------------------------------------------------------------------
1 | {{{result.url}}}
--------------------------------------------------------------------------------
/msg/youtube_error.md:
--------------------------------------------------------------------------------
1 | Could not fetch Youtube video.
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "matlab-discord-bot",
3 | "version": "1.0.3",
4 | "description": "A bot for the Matlab server on Discord.",
5 | "main": "index.js",
6 | "scripts": {
7 | "start": "node index.js",
8 | "test": "node ./test/main.js"
9 | },
10 | "keywords": [
11 | "matlab",
12 | "discord",
13 | "bot"
14 | ],
15 | "author": "matlab-discord",
16 | "license": "GPL-3.0",
17 | "dependencies": {
18 | "@discordjs/builders": "^0.11.0",
19 | "@discordjs/rest": "^0.2.0-canary.0",
20 | "cheerio": "^1.0.0-rc.2",
21 | "discord-api-types": "^0.26.1",
22 | "discord.js": "^13.6.0",
23 | "dotenv": "^6.0.0",
24 | "mustache": "^2.3.0",
25 | "request": "^2.87.0",
26 | "request-promise": "^4.2.6"
27 | },
28 | "devDependencies": {
29 | "eslint": "^8.7.0",
30 | "eslint-config-airbnb-base": "^15.0.0",
31 | "eslint-plugin-import": "^2.25.4",
32 | "eslint-plugin-react": "^7.28.0",
33 | "nodemon": "^2.0.15"
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/src/cronjobs.js:
--------------------------------------------------------------------------------
1 | const fs = require('fs');
2 | const mustache = require('mustache');
3 | const templates = require('./templates');
4 | const { getNewestBlogEntry, getNewestTweet, getNewestVideo } = require('./mathworks-docs');
5 |
6 | const cronjob_data_file = './storage/cronjob_data.json';
7 |
8 | // const cronjobs = [
9 | // {
10 | // name: 'Blog',
11 | // use: getNewestBlogEntry,
12 | // interval: 3 * 3600 * 1e3,
13 | // template: 'blog.md',
14 | // errors: [],
15 | // }, {
16 | // name: 'Twitter',
17 | // use: getNewestTweet,
18 | // interval: 1 * 3600 * 1e3,
19 | // template: 'twitter.md',
20 | // errors: [],
21 | // }, {
22 | // name: 'Youtube',
23 | // use: getNewestVideo,
24 | // interval: 2 * 3600 * 1e3,
25 | // template: 'youtube.md',
26 | // errors: [],
27 | // },
28 | // ];
29 |
30 | // TODO - Mathworks cut us off from all the API's :'( sad day
31 | // Twitter API is dead as well
32 | const cronjobs = [];
33 |
34 | if (!fs.existsSync(cronjob_data_file)) {
35 | console.log("Couldn't find cronjob data file, creating empty version");
36 | fs.writeFileSync(cronjob_data_file, "{}", "utf8");
37 | }
38 |
39 | const cronjob_data = JSON.parse(fs.readFileSync(cronjob_data_file, 'utf8'));
40 |
41 | module.exports = {
42 | initCronJobs(client) {
43 | for (const cronjob of cronjobs) {
44 | // Check if this cronjob type has a reference in the data JSON, if not, add a blank value
45 | if (!cronjob_data.hasOwnProperty(cronjob.name)) {
46 | cronjob_data[cronjob.name] = { entry: { title: '' } };
47 | }
48 |
49 | cronjob.use()
50 | .then((entry) => {
51 | cronjob.last_checked = new Date();
52 | if (cronjob_data[cronjob.name].entry.title !== entry.title) {
53 | // record the entry to the data json
54 | cronjob_data[cronjob.name].entry = entry;
55 |
56 | // On boot, submit the news if it's..... new
57 | client.channels.fetch(process.env.NEWS_CHANNEL_ID)
58 | .then((channel) => channel.send(mustache.render(templates[cronjob.template], { result: entry })));
59 | }
60 |
61 | // Run cronjob
62 | setInterval(() => {
63 | cronjob.use()
64 | .then((entry) => {
65 | cronjob.last_checked = new Date();
66 | // The latest entry hasn't changed, just return out
67 | // if (entry.title === cronjob.entry.title) {
68 | if (entry.title === cronjob_data[cronjob.name].entry.title) {
69 | return;
70 | }
71 | cronjob_data[cronjob.name].entry = entry;
72 | // Update with the newest entry and post to discord
73 | cronjob.entry = entry;
74 | // Write the cronjob data file out to update the last news IDS
75 | fs.writeFileSync(cronjob_data_file, JSON.stringify(cronjob_data));
76 | // Send the news
77 | client.channels.fetch(process.env.NEWS_CHANNEL_ID)
78 | .then((channel) => channel.send(mustache.render(templates[cronjob.template], { result: entry })));
79 | })
80 | .catch((error) => {
81 | if (error) {
82 | cronjob.errors.push(error);
83 | console.log(error);
84 | }
85 | });
86 | }, cronjob.interval);
87 |
88 | // Write the cronjob data file out to update the last news IDS
89 | fs.writeFileSync(cronjob_data_file, JSON.stringify(cronjob_data));
90 | })
91 | .catch((error) => {
92 | cronjob.errors.push(error);
93 | console.log(error);
94 | });
95 | }
96 | },
97 | };
98 |
--------------------------------------------------------------------------------
/src/download.js:
--------------------------------------------------------------------------------
1 | const request = require('request');
2 | const fs = require('fs');
3 |
4 | const download = function (uri, filename, callback) {
5 | request(uri).pipe(fs.createWriteStream(filename)).on('close', callback);
6 | };
7 |
8 | module.exports = download;
--------------------------------------------------------------------------------
/src/fetch.js:
--------------------------------------------------------------------------------
1 | const request = require('request');
2 | const cheerio = require('cheerio');
3 |
4 | const fetch = (url, type = 'html') => new Promise((resolve, reject) => {
5 | request(url, (error, res, html) => {
6 | if (error) {
7 | reject(error);
8 | }
9 | if (type === 'json') {
10 | try {
11 | resolve(JSON.parse(html));
12 | } catch (error) {
13 | reject(error);
14 | }
15 | } else if (type === 'html') {
16 | resolve(cheerio.load(html));
17 | } else {
18 | resolve(html);
19 | }
20 | });
21 | });
22 |
23 | module.exports = fetch;
24 |
--------------------------------------------------------------------------------
/src/inchat-octave.js:
--------------------------------------------------------------------------------
1 | const fs = require('fs');
2 | const { exec } = require('child_process');
3 | const util = require('util');
4 | const download = require('./download');
5 |
6 | const lengthMaxBotMessages = 1000; // max message length
7 |
8 | // Define the path variables for inchat octave
9 | const ic_octave_folder = './inchat_octave';
10 | const ic_octave_workspaces = util.format('%s/workspaces', ic_octave_folder);
11 | const ic_octave_out_file = util.format('%s/bot_out.txt', ic_octave_folder);
12 | const ic_octave_user_code = util.format('%s/user_code.m', ic_octave_folder);
13 | const ic_octave_printout = util.format('%s/user_printout.png', ic_octave_folder);
14 | const ic_octave_timeout = 5000; // time in ms
15 |
16 | // Load in illegal use functions for inchat octave and compile them as a regexp
17 | const illegal_read = fs.readFileSync(util.format('%s/illegal_phrases', ic_octave_folder), 'utf8');
18 | const illegal_use_regexp = new RegExp(`(${illegal_read.replace(/\n/g, ')|(')})`);
19 |
20 | function octaveRun(msg, operation) {
21 | // Figure out the workspace filename for this user
22 | const user_id = `${msg.author.username}#${msg.author.discriminator}`;
23 | const user_work_file = `${ic_octave_workspaces}/${user_id}.mat`;
24 |
25 | const oct_call_regexp = /!o\w+\s*(?:```matlab)?([\s\S.]*[^`])(?:```)?$/;
26 | const oct_call_tokens = msg.content.match(oct_call_regexp);
27 |
28 | // Grab the users commands
29 | const code = oct_call_tokens[1];
30 |
31 | // Check for illegal command usage and warn against it...
32 | const found_illegal_match = code.match(illegal_use_regexp);
33 | if (found_illegal_match) {
34 | msg.channel.send(`Someone was being naughty <@${process.env.OWNER_ID}>`);
35 | return;
36 | }
37 |
38 | // Write the users code command to a file. continue execution if it works
39 | fs.writeFile(ic_octave_user_code, code, (err) => {
40 | // Check for a file write error
41 | if (err) {
42 | console.log('--------- FILE WRITE ERROR ----------------');
43 | console.log(err);
44 | msg.channel.send(`Something went wrong. <@${process.env.OWNER_ID}>`);
45 | return;
46 | }
47 |
48 | // Format system call for octave CLI
49 | const cmd_format = util.format('addpath(\'%s\'); bot_runner(\'%s\', \'%s\')', ic_octave_folder, ic_octave_out_file, user_work_file);
50 | const octave_call = util.format('octave --no-gui --eval "%s"', cmd_format);
51 |
52 | // Call async system octave call with a timeout. error if it exceeds
53 | exec(octave_call, { timeout: ic_octave_timeout }, (err, stdout, stderr) => {
54 | if (err) { // if there was an error
55 | console.log(err); // log the error
56 | msg.channel.send('Your command timed out.');
57 | } else { // Read the output file
58 | fs.readFile(ic_octave_out_file, 'utf8', (err, data) => {
59 | if (err) {
60 | console.log('--------- FILE READ ERROR ----------------');
61 | console.log(err);
62 | console.log(ic_octave_out_file);
63 | msg.channel.send(`Something went wrong. <@${process.env.OWNER_ID}>`);
64 | } else { // Send the output file message
65 | // Make sure it doesn't exceed the max message length before sending
66 | const msg_out = util.format('```matlab\n%s```', data);
67 | if (msg_out.length >= lengthMaxBotMessages) {
68 | msg.channel.send({files: ['./inchat_octave/bot_out.txt']});
69 | } else if (operation === 'orun') { // special case to post non formatted
70 | msg.channel.send(util.format('%s', data));
71 | } else {
72 | msg.channel.send(util.format('```matlab\n%s```', data));
73 | }
74 | }
75 | });
76 | }
77 | });
78 | });
79 | }
80 |
81 | function octavePrint(msg) {
82 | // Figure out the workspace filename for this user
83 | const user_id = `${msg.author.username}#${msg.author.discriminator}`;
84 | const user_work_file = `${ic_octave_workspaces}/${user_id}.mat`;
85 |
86 | const cmd_format = util.format('addpath(\'%s\'); print_user_gcf(\'%s\', \'%s\')', ic_octave_folder, user_work_file, ic_octave_printout);
87 | const octave_call = util.format('octave --no-gui --eval "%s"', cmd_format);
88 |
89 | // Call async system octave call with a timeout. error if it exceeds
90 | exec(octave_call, { timeout: 20000 }, (err, stdout, stderr) => {
91 | if (err) { // if there was an error
92 | console.log(err); // log the error
93 | msg.channel.send('You don\'t have a graphics figure generated.');
94 | } else { // Read the output file
95 | msg.channel.send('', { files: [ic_octave_printout] });
96 | }
97 | });
98 | }
99 |
100 | function octaveUpload(msg) {
101 | // Figure out the workspace filename for this user
102 | const user_id = `${msg.author.username}#${msg.author.discriminator}`;
103 | const user_work_file = `${ic_octave_workspaces}/${user_id}.mat`;
104 |
105 | // Check if there were any attachments with this message
106 | if (msg.attachments.size === 0) {
107 | msg.channel.send('Nothing was uploaded.');
108 | return;
109 | }
110 |
111 | // Valid image type extensions
112 | const valid_filetypes_regexp = /.*\.(mat|png|jpe?g|gif|tif{1,2})/;
113 |
114 | // Grab the message attachment
115 | const msg_attachment = msg.attachments.values().next().value;
116 |
117 | // Get the attachment filetype this user uploaded
118 | const attachment_filetype = msg_attachment.filename.match(valid_filetypes_regexp);
119 |
120 | // Check if the uploaded attachment is a valid image type
121 | if (attachment_filetype === null) {
122 | msg.channel.send('Invalid image type. Can\'t upload.');
123 | return;
124 | }
125 | let filetype;
126 | switch (attachment_filetype[1]) {
127 | case 'mat':
128 | filetype = 'data';
129 | break;
130 |
131 | default:
132 | filetype = 'image';
133 | break;
134 | }
135 |
136 | // Grab the variable name for the image upload
137 | const upload_filename = util.format('%s/user_upload.%s', ic_octave_folder, attachment_filetype[1]);
138 |
139 | // Download the image from discord URL, then read into octave and save to the users workspace
140 | download(msg_attachment.url, upload_filename, () => {
141 | let out_msg;
142 | let cmd_format;
143 | switch (filetype) {
144 | case 'data':
145 | cmd_format = util.format('addpath(\'%s\'); load_user_data(\'%s\', \'%s\')', ic_octave_folder, user_work_file, upload_filename);
146 | out_msg = 'Data uploaded to your workspace.';
147 | break;
148 |
149 | case 'image':
150 | cmd_format = util.format('addpath(\'%s\'); load_user_img(\'%s\', \'%s\')', ic_octave_folder, user_work_file, upload_filename);
151 | out_msg = 'Image saved to your workspace as variable `img`.';
152 | break;
153 | }
154 | // var cmd_format = util.format(`addpath('%s'); load_user_img('%s', '%s')`, ic_octave_folder, user_work_file, upload_filename);
155 | const octave_call = util.format('octave --no-gui --eval "%s"', cmd_format);
156 |
157 | // Call async system octave call with a timeout. error if it exceeds
158 | exec(octave_call, { timeout: 20000 }, (err, stdout, stderr) => {
159 | if (err) { // if there was an error
160 | console.log(err); // log the error
161 | msg.channel.send(`Something went wrong. <@${process.env.OWNER_ID}>`);
162 | } else { // Read the output file
163 | msg.channel.send(out_msg);
164 | }
165 | });
166 | });
167 | }
168 |
169 | function octaveExecute(msg, tokens) {
170 | // Don't allow the use of this function in DM's
171 | // if((msg.guild === null) && (msg.author.id != process.env.OWNER_ID)) {
172 | if (!msg.inGuild()) {
173 | msg.channel.send('Use of all Octave functions are not allowed in DM\'s. Please visit the main channel.');
174 | return;
175 | }
176 |
177 | // Grab the octave operation that the user called
178 | const operation = tokens[1];
179 |
180 | // Control switch for different inchat octave operations
181 | switch (operation) {
182 | // Typical command. Run/compute user code
183 | case 'oct':
184 | case 'octave':
185 | case 'orun':
186 | octaveRun(msg, operation);
187 | break;
188 |
189 | // Octave Print. Print the current users graphic figure saved in the workspace to chat
190 | case 'opr':
191 | case 'oprint':
192 | case 'octaveprint':
193 | octavePrint(msg);
194 | break;
195 |
196 | // Octave upload. Upload attached image to users workspace
197 | case 'oup':
198 | case 'oupload':
199 | case 'octaveupload':
200 | octaveUpload(msg);
201 | break;
202 |
203 | default:
204 | // nothing
205 | break;
206 | }
207 | }
208 |
209 | // Function to clear out workspace `.mat` files
210 | async function clearWorkspaces() {
211 | // Directory location for the workspace files
212 | const workspace_location = './inchat_octave/workspaces';
213 |
214 | // Read the directory and look through each file.
215 | fs.readdir(workspace_location, (err, files) => {
216 | if (err) throw err;
217 |
218 | // Filter out any file that doesn't have `.mat` in its name
219 | files.filter((name) => {
220 | const regexp = new RegExp('\.mat');
221 | return regexp.test(name);
222 | }).forEach((file) => { // Delete each file (unlink)
223 | // Remove each .mat file we found in the workspace
224 | fs.unlink(`${workspace_location}/${file}`, (err) => {
225 | if (err) throw err;
226 | console.log(`${workspace_location}/${file} removed`);
227 | });
228 | });
229 | });
230 | }
231 |
232 | module.exports = {
233 | octaveExecute,
234 | clearWorkspaces,
235 | };
236 |
--------------------------------------------------------------------------------
/src/latex.js:
--------------------------------------------------------------------------------
1 | const util = require('util');
2 |
3 | // Host site for url fetch
4 | const host = 'https://chart.apis.google.com/chart?';
5 |
6 | async function latex2pngurl(latex) {
7 | // Establish paramters that configure the look of the latex
8 | const config = {
9 | bgcolor: '36393F',
10 | alpha: '80',
11 | textcolor: 'FFFFFF',
12 | height: 40,
13 | };
14 |
15 | // Build the latex URL relevent to our host
16 | return util.format('%scht=tx&chl=%s&chs=%d&chf=bg,s,%s%s&chco=%s', host, encodeURIComponent(latex), config.height, config.bgcolor, config.alpha, config.textcolor);
17 |
18 | }
19 |
20 | // could maybe use for more encoding options? don't think it's necessary
21 | // function urlencode(str) {
22 | // str = (str + '').toString();
23 |
24 | // // Tilde should be allowed unescaped in future versions of PHP (as reflected below), but if you want to reflect current
25 | // // PHP behavior, you would need to add ".replace(/~/g, '%7E');" to the following.
26 | // return encodeURIComponent(str)
27 | // .replace('!', '%21')
28 | // .replace('\'', '%27')
29 | // .replace('(', '%28')
30 | // .replace(')', '%29')
31 | // .replace('*', '%2A')
32 | // .replace('%20', '+');
33 | // }
34 |
35 | module.exports = latex2pngurl;
36 |
--------------------------------------------------------------------------------
/src/mathworks-docs.js:
--------------------------------------------------------------------------------
1 | const request = require('request-promise');
2 | const DOC_VER = "R2025a";
3 | // Enum const to differentiate between OK and FAILED responses
4 | const RESPONSE = {
5 | OK: true,
6 | FAIL: false
7 | }
8 |
9 | // Private generalized query function
10 | async function __docQuery(queryURL) {
11 | // Spoofing the query to get through akami firewall.... It doesn't like bot request :'(
12 | const response = await fetch(queryURL, {
13 | headers: {
14 | 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36',
15 | 'Referer': 'https://www.mathworks.com/',
16 | 'Accept': 'application/json'
17 | }
18 | });
19 |
20 | if (!response.ok) {
21 | return (
22 | {
23 | url: `HTTP error! Status: ${response.status} - ${response.statusText}`,
24 | response: RESPONSE.FAIL
25 | });
26 | }
27 | const data = await response.json(); // Correct way to parse JSON
28 | let _check = data.pages || data.items;
29 | if (!_check || _check.length === 0) {
30 | return ({
31 | url: "No information found in the response data.",
32 | response: RESPONSE.FAIL
33 |
34 | })
35 | }
36 |
37 | // Add in the response information
38 | data.response = RESPONSE.OK;
39 | return data;
40 | }
41 |
42 | async function docAutocomplete(query) {
43 | const queryURL = `https://mathworks.com/help/search/suggest/doccenter/en/${DOC_VER}?q=${encodeURIComponent(query)}`;
44 | const d = await __docQuery(queryURL);
45 | const docSuggestions = d.pages.flatMap(
46 | (page) => page.suggestions.map(
47 | (suggestion) => (
48 | {
49 | name: `${suggestion.product} - ${(/\/([0-9a-zA-Z.]*)\.html/.exec(suggestion.path))[1]}`,
50 | value: suggestion.path,
51 | }
52 | )
53 | )
54 | );
55 | return docSuggestions;
56 | }
57 |
58 | async function searchDocs(query) {
59 | const queryURL = `https://mathworks.com/help/search/suggest/doccenter/en/${DOC_VER}?q=${encodeURIComponent(query)}`;
60 | const data = await __docQuery(queryURL);
61 | const suggestion = data.pages[0].suggestions[0];
62 | return {
63 | title: suggestion.title.join(''),
64 | summary: suggestion.summary.join(''),
65 | product: suggestion.product,
66 | url: `https://mathworks.com/help/${suggestion.path}`,
67 | path: suggestion.path,
68 | };
69 | }
70 |
71 | async function answersAutocomplete(query) {
72 | const queryURL = `https://api.mathworks.com/community/v1/search?scope=matlab-answers&sort_order=relevance+desc&query=${encodeURIComponent(query)}`;
73 | const data = await __docQuery(queryURL);
74 | // Discord answer value suggestions are capped at 100 characters. Makes it so we are unable to supply the full URL. Need to chunk it and reconstruct on the other end..
75 | const docSuggestions = data.items.flatMap(
76 | (item) => {
77 | const url = item.url;
78 | const lastSlash = url.lastIndexOf('/');
79 | const secondLastSlash = url.lastIndexOf('/', lastSlash - 1);
80 | const extractedValue = secondLastSlash !== -1 ? url.slice(secondLastSlash + 1) : url;
81 |
82 | return {
83 | name: `${item.scope}: ${item.title}`,
84 | value: extractedValue
85 | }
86 | }
87 | );
88 | return docSuggestions;
89 | }
90 |
91 | async function searchAnswers(query) {
92 | const queryURL = `https://api.mathworks.com/community/v1/search?scope=matlab-answers&sort_order=relevance+desc&query=${encodeURIComponent(query)}`;
93 | const data = await __docQuery(queryURL);
94 | const suggestion = data.items[0]
95 | return {
96 | title: suggestion.title,
97 | description: suggestion.summary,
98 | product: suggestion.product,
99 | url: suggestion.url,
100 | description: suggestion.description,
101 | };
102 | }
103 |
104 | // Grabbing latest blog entry
105 | async function getNewestBlogEntry() {
106 | const d = await (await fetch('https://blogs.mathworks.com/')).json();
107 | const [, , date] = /^(.*?)on (.+)$/.exec(d('.blogger-name').eq(0).text().trim());
108 | const a = d('.post-title > a').eq(0);
109 | return {
110 | title: a.text().trim(),
111 | url: a.attr('href'),
112 | date,
113 | datenum: parseDate(date),
114 | };
115 | }
116 |
117 | // Grabbing latest tweet
118 | async function getNewestTweet() {
119 | // Use an HTTPS request with the twitter v2 API to grab the 20 latest tweets from the @MATLAB account.
120 | // Search for the newest self published tweet (no quotes, no retweets, etc)
121 | const latestTweet = await request.get('https://api.twitter.com/2/tweets/search/recent?query=from:MATLAB&tweet.fields=created_at,id,lang,referenced_tweets&expansions=author_id&user.fields=created_at&max_results=20', {
122 | json: true,
123 | auth: {
124 | bearer: process.env.TWITTER_BEARER_TOKEN,
125 | },
126 | }).then((body) => {
127 | // If there was an error, return JSON with "error" field
128 | if (!('data' in body)) {
129 | throw ('No tweets found in last 7 days from API request. (Account is no longer active?)');
130 | }
131 |
132 | // Look for the first non referenced tweet and return it
133 | for (let i = 0; i < body.data.length; i++) {
134 | if (!('referenced_tweets' in body.data[i])) {
135 | return {
136 | title: body.data[i].id,
137 | url: `https://twitter.com/MATLAB/status/${body.data[i].id}`,
138 | };
139 | }
140 | }
141 |
142 | // If we got this far, this means there are no original tweets to post, only retweets... throw error.
143 | // Kinda dumb way to handle this, but it works good 'nuff
144 | throw ('Account only contains retweets');
145 | }).catch((err) => {
146 | // Want to throw the other errors so that they are caught by the cronjob
147 | throw (err);
148 | });
149 |
150 | return latestTweet;
151 | }
152 |
153 | // Grabbing latest youtube video
154 | async function getNewestVideo() {
155 | // Grab the google APIs token
156 | const token = process.env.YOUTUBE_AUTH_KEY;
157 | const queryURL = "https://www.googleapis.com/youtube/v3/search?key=${token}&channelId=UCgdHSFcXvkN6O3NXvif0-pA&part=snippet,id&order=date&maxResults=1";
158 | const response = await fetch(queryURL);
159 | const video = response.json().items[0];
160 | return {
161 | title: video.snippet.title,
162 | description: video.snippet.description,
163 | url: `https://youtube.com/watch?v=${video.id.videoId}`,
164 | date: video.snippet.publishedAt,
165 | };
166 | }
167 |
168 | function parseDate(date) {
169 | const currentYear = (new Date()).getFullYear().toString();
170 | if (!date.endsWith(currentYear)) {
171 | date += `, ${currentYear}`;
172 | }
173 | return Date.parse(date);
174 | }
175 |
176 | module.exports = {
177 | docAutocomplete,
178 | searchDocs,
179 | answersAutocomplete,
180 | searchAnswers,
181 | getNewestBlogEntry,
182 | getNewestTweet,
183 | getNewestVideo,
184 | };
185 |
--------------------------------------------------------------------------------
/src/minesweeper.js:
--------------------------------------------------------------------------------
1 | function shuffle(a) {
2 | let j; let x; let
3 | i;
4 | for (i = a.length - 1; i > 0; i--) {
5 | j = Math.floor(Math.random() * (i + 1));
6 | x = a[i];
7 | a[i] = a[j];
8 | a[j] = x;
9 | }
10 | return a;
11 | }
12 |
13 | const buildMinesweeperGrid = function (grid_size, perc_mines) {
14 | const grid = Array(grid_size).fill().map(() => Array(grid_size));
15 | const num_mines = Math.round(grid_size * grid_size * (perc_mines / 100));
16 |
17 | const num_spaces = grid_size * grid_size;
18 | const mines_index = shuffle(Array.from(Array(num_spaces).keys())).slice(0, num_mines);
19 | const mine_string = '||` M `||';
20 | // Add the mines
21 | for (var i = 0; i < grid_size; i++) {
22 | for (var j = 0; j < grid_size; j++) {
23 | if (mines_index.includes(i * grid_size + j)) {
24 | grid[i][j] = mine_string;
25 | }
26 | }
27 | }
28 |
29 | let mine_count_this_grid = 0;
30 | // Add the numbers
31 | for (let i = 0; i < grid_size; i++) {
32 | for (let j = 0; j < grid_size; j++) {
33 | if (grid[i][j] === mine_string) {
34 | continue;
35 | }
36 | mine_count_this_grid = 0;
37 | for (let k = -1; k <= 1; k++) {
38 | if ((i - k) < 0 || (i - k) > (grid_size - 1)) {
39 | continue;
40 | }
41 | for (let z = -1; z <= 1; z++) {
42 | if ((j - z) < 0 || (j - z) > (grid_size - 1)) {
43 | continue;
44 | } else if (grid[i - k][j - z] === mine_string) {
45 | mine_count_this_grid++;
46 | }
47 | }
48 | }
49 | grid[i][j] = `||\` ${mine_count_this_grid.toString()} \`||`;
50 | }
51 | }
52 |
53 | let discordMinesweeperGrid = `Total Spaces: ${num_spaces} Total Mines: ${num_mines}\n`;
54 | // Build the final string
55 | for (let i = 0; i < grid_size; i++) {
56 | for (let j = 0; j < grid_size; j++) {
57 | discordMinesweeperGrid += `${grid[i][j]} `;
58 | }
59 | discordMinesweeperGrid += '\n';
60 | }
61 |
62 | return discordMinesweeperGrid;
63 | };
64 |
65 | module.exports = buildMinesweeperGrid;
66 |
--------------------------------------------------------------------------------
/src/render.js:
--------------------------------------------------------------------------------
1 | const mustache = require('mustache');
2 | const templates = require('./templates');
3 |
4 | const renderMsg = async function (msg, filename, view = {}, opts = {}, deleteMsg = false) {
5 | if (templates[filename] === undefined) {
6 | return;
7 | }
8 | const sent = await msg.channel.send(mustache.render(templates[filename], view), opts).catch(console.log);
9 | if (sent !== undefined) {
10 | if (deleteMsg) {
11 | msg.delete(20).catch(console.error);
12 | }
13 | }
14 | };
15 |
16 | const renderInter = async function (interaction, filename, view = {}, opts = {}, hiddenSender = false) {
17 | if (templates[filename] === undefined) {
18 | return;
19 | }
20 | if (hiddenSender) {
21 | const message = { content: mustache.render(templates[filename], view), ...opts };
22 | await interaction.channel.send(message).catch(console.log);
23 | await interaction.reply({ content: 'Sent anonymously.', ephemeral: true }).catch(console.log);
24 | } else {
25 | const message = { content: mustache.render(templates[filename], view), ...opts };
26 | await interaction.reply(message).catch(console.log);
27 | }
28 | };
29 |
30 | module.exports = {
31 | renderMsg,
32 | renderInter,
33 | };
34 |
--------------------------------------------------------------------------------
/src/router.js:
--------------------------------------------------------------------------------
1 | const latex = require('./latex');
2 | const {
3 | searchDocs, getNewestBlogEntry, getNewestTweet, getNewestVideo,
4 | } = require('./mathworks-docs');
5 | const { renderMsg: render } = require('./render');
6 | const why = require('./why');
7 | const buildMinesweeperGrid = require('./minesweeper');
8 | const icoct = require('./inchat-octave');
9 | const download = require('./download');
10 |
11 | const router = [
12 | {
13 | regexp: /^!run[\s`]/,
14 | use(msg) {
15 | if (!msg.inGuild()) {
16 | msg.channel.send('Use of in chat MATLAB is not allowed in DM\'s. Please visit the main channel.');
17 | }
18 | },
19 | },
20 | {
21 | // Will take the last posted message and run any code found within a code block (wrapped in backticks ```)
22 | regexp: /^!eval(?:uate)?$/,
23 | use(msg) {
24 | // Define the number of messages the eval call will search back
25 | const MSG_SEARCH_LIM = 10;
26 |
27 | msg.channel.messages.fetch({ limit: MSG_SEARCH_LIM + 1 }) // +1 because we account for the message that called the eval...
28 | .then((messages) => {
29 | const _old_msgs = Array.from(messages.entries()).map((item) => item[1].content);
30 |
31 | // Remove the first message (this is the message that called the eval)
32 | _old_msgs.splice(0, 1);
33 |
34 | // Loop through the messages from newest to oldest, find a valid code block
35 | for (let i = 0; i < _old_msgs.length; i++) {
36 | const codeMsg = _old_msgs[i]; // check the message
37 | const codeSearchRegexp = /```(?:matlab)?(?:\nmatlab)?((\w|\s|\S)*)```/; // regexp to parse user code between code blocks
38 | const codeSearchTokens = codeMsg.match(codeSearchRegexp);
39 | // Couldn't find a match. move onto the next message (if there is one) or break out with error message
40 | if (codeSearchTokens == null) { // couldn't find a match
41 | if (i === _old_msgs.length - 1) { // end of loop
42 | msg.channel.send('Message doesn\'t contain a valid code formatting block. (Wrapped in ```)');
43 | return;
44 | }
45 | continue;
46 | }
47 | const codeToRun = codeSearchTokens[1];
48 | const run_command = `!run\`\`\`matlab\n${codeToRun}\`\`\``;
49 | // Run the code, then delete message immediately
50 | msg.channel.send(run_command).then((msg) => msg.delete(20).catch(console.error));
51 | break; // break out of the loop since we found a valid message
52 | }
53 | });
54 | },
55 | },
56 |
57 | {
58 | // Inchat octave (remove h for octhelp message)
59 | regexp: /^!(oct(?=[^h])|opr|oup|orun)/,
60 | use(msg, tokens) {
61 | icoct.octaveExecute(msg, tokens);
62 | },
63 | },
64 |
65 | {
66 | regexp: /!(m|doc) (.+?)(\s.*)?$/, // E.g. if "!m interp1" or "!doc interp1"
67 | use(msg, tokens) {
68 | const query = tokens[2].trim();
69 | searchDocs(query)
70 | .then((result) => {
71 | result.toolbox = (result.product.toLowerCase() !== 'matlab') ? ` from ${result.product}` : '';
72 | render(msg, 'doc.md', { url: result.url }).catch(console.error);
73 | })
74 | .catch((error) => {
75 | if (error) {
76 | render(msg, 'doc_error.md', { error, query }).catch(console.error);
77 | }
78 | });
79 | },
80 | },
81 | {
82 | regexp: /[[!$]`+([\s\S.]*[^`])`+$/, // Latex parser
83 | use(msg, tokens) {
84 | const query = tokens[1].trim();
85 | latex(query).then((imgUrl) => {
86 | // Download the image from the url (this url is strange, doesn't have an extension ending) then send
87 | download(imgUrl, 'img/latex.png', () => {
88 | msg.channel.send({ content: `Input: \`${query}\``, files: ['./img/latex.png'] })
89 | .then()
90 | .catch(console.error);
91 | });
92 | }).catch((error) => {
93 | if (error) {
94 | msg.channel.send('Could not parse latex.');
95 | }
96 | });
97 | },
98 | },
99 | {
100 | regexp: /!blog/,
101 | use(msg) {
102 | getNewestBlogEntry()
103 | .then((result) => {
104 | render(msg, 'blog.md', { result }).catch(console.error);
105 | })
106 | .catch((error) => {
107 | if (error) {
108 | render(msg, 'blog_error.md', { error }).catch(console.error);
109 | }
110 | });
111 | },
112 | },
113 | {
114 | regexp: /^!minesweeper\s(\d+)(?:\s(\d+))?/,
115 | use(msg, tokens) {
116 | const grid_size = Number(tokens[1]);
117 | let perc_mines;
118 | if (tokens[2] == null) {
119 | perc_mines = 20; // 20 percent by default
120 | } else {
121 | perc_mines = Number(tokens[2]);
122 | }
123 | msg.channel.send(buildMinesweeperGrid(grid_size, perc_mines));
124 | },
125 |
126 | },
127 | {
128 | regexp: /^!google\s*(.*)$/,
129 | use(msg, tokens) {
130 | const str = tokens[1];
131 | let res;
132 | // If the user sent issued the command with no message, use the previous message in chat
133 | if (!str) {
134 | res = msg.channel.messages.array()[msg.channel.messages.size - 2].content;
135 | res = res.replace(/ /g, '+');
136 | } else {
137 | res = str.replace(/ /g, '+');
138 | }
139 | msg.channel.send(`https://lmgtfy.com/?q=${res}`);
140 | msg.delete(20).catch(console.error);
141 | },
142 | },
143 | {
144 | regexp: /((''')|('''matlab))[\S\s.]*'''/,
145 | use(msg) {
146 | const opts = { files: ['./img/backtick_highlight.png'] };
147 | render(msg, 'code.md', { query: 'code' }, opts, false).catch(console.error);
148 | },
149 | },
150 | {
151 | regexp: /!youtube/,
152 | use(msg) {
153 | getNewestVideo()
154 | .then((result) => {
155 | render(msg, 'youtube.md', { result }).catch(console.error);
156 | })
157 | .catch((error) => {
158 | if (error) {
159 | render(msg, 'youtube_error.md', { error }).catch(console.error);
160 | }
161 | });
162 | },
163 | },
164 | {
165 | regexp: /!twitter/,
166 | use(msg) {
167 | getNewestTweet()
168 | .then((result) => {
169 | render(msg, 'twitter.md', { result }).catch(console.error);
170 | })
171 | .catch((error) => {
172 | if (error) {
173 | render(msg, 'twitter_error.md', { error }).catch(console.error);
174 | }
175 | });
176 | },
177 | },
178 | {
179 | regexp: /^!why\s*(.*)$/,
180 | use(msg, tokens) {
181 | const str = tokens[1];
182 | render(msg, 'why.md', {
183 | question: str,
184 | result: why(),
185 | }).catch(console.error);
186 | },
187 | },
188 | {
189 | regexp: /^!(done|close|finish|answered|exit)/, // allow users to clear the busy status of help channels
190 | use(msg, _, client) {
191 | if (!client.help_channel_ids.includes(msg.channel.id)) {
192 | msg.channel.send('Use this command in a help-channel to clear its busy status once a question is complete.');
193 | }
194 |
195 | // check if the channel is a help channel first
196 | const chan = msg.channel;
197 | const chan_ind = client.help_channel_ids.indexOf(chan.id);
198 |
199 | // If the help channel is busy, clear its busy status
200 | if (client.help_channel_ids[chan_ind] != null) {
201 | clearTimeout(client.help_channel_timers[chan_ind]);
202 | client.help_channel_timers[chan_ind] = null;
203 | chan.setName(client.help_channel_names[chan_ind]);
204 | msg.channel.send('Channel is available for another question.');
205 | msg.delete(20).catch(console.error);
206 | } else {
207 | // The user executed the command in a question channel that isn't busy
208 | msg.channel.send('Channel is available for another question.');
209 | msg.delete(20).catch(console.error);
210 | }
211 | },
212 | },
213 | {
214 | regexp: /^!(.+?)( .*)?$/, // E.g. any other message, pass-through (like help.md => "!help", "!help interp1", ...)
215 | use(msg, tokens) {
216 | const command = tokens[1];
217 |
218 | // For an extra layer of configurability, some pass-through messages can have options (dont delete message, add file)
219 | let opts = {};
220 | let delete_msg = true;
221 | switch (command) {
222 | case 'code':
223 | // Send keyboard image with code command
224 | opts = { files: ['./img/backtick_highlight.png'] };
225 | break;
226 |
227 | case 'jobs':
228 | case 'help':
229 | case 'mathelp':
230 | case 'octhelp':
231 | // Preferablly keep the message on to see who is looking at jobs
232 | delete_msg = false;
233 | break;
234 | default:
235 | // do nothing
236 | } // end switch
237 |
238 | // Render the message with arguments
239 | render(msg, `${command}.md`, { query: command }, opts, delete_msg).catch(console.error);
240 | },
241 | },
242 | {
243 | regexp: /^!askgood\s*(.*)$/, // "!askgood @user" shows some asking tips and pings the user
244 | use(msg, tokens) {
245 | const username = tokens[2].trim;
246 | render(msg, 'askgood.md', { username }).catch(console.error);
247 | },
248 | }];
249 |
250 | module.exports = router;
251 |
--------------------------------------------------------------------------------
/src/templates.js:
--------------------------------------------------------------------------------
1 | const fs = require('fs');
2 |
3 | const readFiles = function (dirname, encoding = 'utf8') {
4 | const files = {};
5 | fs.readdirSync(dirname).forEach((filename) => {
6 | files[filename] = fs.readFileSync(dirname + filename, encoding);
7 | });
8 | return files;
9 | };
10 |
11 | const templates = readFiles('./msg/');
12 |
13 | module.exports = templates;
14 |
--------------------------------------------------------------------------------
/src/why.js:
--------------------------------------------------------------------------------
1 | function sample(array) {
2 | // Return random sample from an array
3 | return array[Math.floor(Math.random() * array.length)];
4 | }
5 |
6 | function weightedSample(data) {
7 | // Given a dictionary { object : weight } return a weighted random sample
8 | const totalSum = Object.values(data).reduce((a, b) => a + b, 0);
9 | const numElements = Object.values(data).length;
10 | const randNum = Math.random() * totalSum;
11 | let threshold = 0;
12 | for (let i = 0; i < numElements; i++) {
13 | threshold += parseFloat(Object.values(data)[i]);
14 | if (threshold > randNum) {
15 | return Object.keys(data)[i];
16 | }
17 | }
18 | }
19 |
20 | const specialCase = () => sample(
21 | [
22 | 'why not?',
23 | 'don\'t ask!',
24 | 'it\'s your karma.',
25 | 'stupid question!',
26 | 'how should I know?',
27 | 'can you rephrase that?',
28 | 'it should be obvious.',
29 | 'the devil made me do it.',
30 | 'the computer did it.',
31 | 'the customer is always right.',
32 | 'in the beginning, God created the heavens and the earth...',
33 | 'don\'t you have something better to do?',
34 | ],
35 | );
36 |
37 | const properNoun = () => sample(
38 | ['Cleve', 'Jack', 'Bill', 'Joe', 'Pete', 'Loren', 'Damian', 'Barney', 'Nausheen', 'Mary Ann', 'Penny', 'Mara'],
39 | );
40 |
41 | const noun = () => sample(
42 | ['mathematician', 'programmer', 'system manager', 'engineer', 'hamster', 'kid'],
43 | );
44 |
45 | const nounedVerb = () => sample(['love', 'approval']);
46 |
47 | const adjective = () => sample(['tall', 'bald', 'young', 'smart', 'rich', 'terrified', 'good']);
48 |
49 | const presentVerb = () => sample(['fool', 'please', 'satisfy']);
50 | const transitiveVerb = () => sample(['threatened', 'told', 'asked', 'helped', 'obeyed']);
51 | const intransitiveVerb = () => sample(['insisted on it', 'suggested it', 'told me to', 'wanted it', 'knew it was a good idea', 'wanted it that way']);
52 |
53 | const article = () => sample(['the', 'some', 'a']);
54 | const nominativePronoun = () => sample(['I', 'you', 'he', 'she', 'they']);
55 | const accusativePronoun = () => sample(['me', 'all', 'her', 'him']);
56 |
57 | const preposition = () => sample(['of', 'from']);
58 | const adverb = () => sample(['very', 'not very', 'not excessively']);
59 |
60 | const phrase = () => sample([
61 | `for the ${nounedVerb()} ${prepositionalPhrase()}.`,
62 | `to ${presentVerb()} ${object()}.`,
63 | `because ${sentence()}`,
64 | ]);
65 |
66 | let prepositionalPhrase = () => sample([
67 | `${preposition()} ${article()} ${nounPhrase()}`,
68 | `${preposition()} ${properNoun()}`,
69 | `${preposition()} ${accusativePronoun()}`,
70 | ]);
71 |
72 | let sentence = () => `${subject()} ${predicate()}.`;
73 |
74 | let subject = () => weightedSample({
75 | [properNoun()]: 1,
76 | [nominativePronoun()]: 1,
77 | [`${article()} ${nounPhrase()}`]: 2,
78 | });
79 |
80 | let object = () => weightedSample({
81 | [accusativePronoun()]: 1,
82 | [`${article()} ${nounPhrase()}`]: 9,
83 | });
84 |
85 | let predicate = () => weightedSample({
86 | [`${transitiveVerb()} ${object()}`]: 1,
87 | [intransitiveVerb()]: 2,
88 | });
89 |
90 | /*
91 | Due to the recursion in nounPhrase and adjectivePhrase, if the same pattern as the other functions is used,
92 | a call stack size exceeded error will occur.
93 | */
94 | // let nounPhrase = () => weightedSample({
95 | // [noun()] : 1,
96 | // // [`${adjectivePhrase()} ${nounPhrase()}`] : 1,
97 | // [`${adjectivePhrase()} ${noun()}`] : 2
98 | // });
99 |
100 | // function adjectivePhrase() {
101 | // return weightedSample({
102 | // [adjective()]: 3,
103 | // // [`${adjectivePhrase()} and ${adjectivePhrase()}`]: 1,
104 | // [`${adverb()} ${adjective()}`]: 1
105 | // })
106 | // }
107 |
108 | const randi = (n) => Math.round((n - 1) * Math.random()) + 1;
109 | function nounPhrase() {
110 | let a;
111 | switch (randi(4)) {
112 | case 1:
113 | a = noun();
114 | break;
115 | case 2:
116 | a = [adjectivePhrase(), ' ', nounPhrase()].join('');
117 | break;
118 | default:
119 | a = [adjectivePhrase(), ' ', noun()].join('');
120 | break;
121 | }
122 | return a;
123 | }
124 | function adjectivePhrase() {
125 | let a;
126 | switch (randi(6)) {
127 | case 1:
128 | case 2:
129 | case 3:
130 | a = adjective();
131 | break;
132 | case 4:
133 | case 5:
134 | a = [adjectivePhrase(), ' and ', adjectivePhrase()].join('');
135 | break;
136 | case 6:
137 | a = [adverb(), ' ', adjective()].join('');
138 | }
139 | return a;
140 | }
141 |
142 | const why = () => {
143 | const whyResult = weightedSample({ [specialCase()]: 1, [phrase()]: 3, [sentence()]: 6 });
144 | return whyResult[0].toUpperCase() + whyResult.substr(1);
145 | };
146 |
147 | module.exports = why;
148 |
--------------------------------------------------------------------------------
/storage/.gitkeep:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/matlab-discord/Matlab-Discord-Bot/def92d900a112d08be6959a19b34631a852d0726/storage/.gitkeep
--------------------------------------------------------------------------------