Skip to content

Commit a815165

Browse files
authored
Integration tutorial example - YodaSpeak (demisto#16403)
demo integration, modernized.
1 parent a38828a commit a815165

20 files changed

Lines changed: 928 additions & 239 deletions

docs/tutorial-video/Integration-Yoda_Speak.yml

Lines changed: 0 additions & 140 deletions
This file was deleted.

docs/tutorial-video/README.md

Lines changed: 0 additions & 3 deletions
This file was deleted.

docs/tutorial-video/YodaSpeak/.pack-ignore

Whitespace-only changes.

docs/tutorial-video/YodaSpeak/.secrets-ignore

Whitespace-only changes.
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
[[source]]
2+
name = "pypi"
3+
url = "https://pypi.org/simple"
4+
verify_ssl = true
5+
6+
[dev-packages]
7+
pylint = "*"
8+
pytest = "==5.0.1"
9+
pytest-mock = "*"
10+
requests-mock = "*"
11+
pytest-asyncio = "*"
12+
13+
[packages]
14+
pytest = "*"
15+
requests = "*"
16+
17+
[requires]
18+
python_version = "3.7"

docs/tutorial-video/YodaSpeak/Integrations/YodaSpeak/Pipfile.lock

Lines changed: 369 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.
Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
An integration to translate English to Yodish.
2+
3+
## Configure YodaSpeak on Cortex XSOAR
4+
5+
1. Navigate to **Settings** > **Integrations** > **Servers & Services**.
6+
2. Search for YodaSpeak.
7+
3. Click **Add instance** to create and configure a new integration instance.
8+
9+
| **Parameter** | **Description** | **Required** |
10+
| --- | --- | --- |
11+
| Base URL of the service | | True |
12+
| API Key | The API Key to use for connection | False |
13+
| Trust any certificate (not secure) | | False |
14+
| Use system proxy settings | | False |
15+
16+
4. Click **Test** to validate the URLs, token, and connection.
17+
## Commands
18+
You can execute these commands from the Cortex XSOAR CLI, as part of an automation, or in a playbook.
19+
After you successfully execute a command, a DBot message appears in the War Room with the command details.
20+
### yoda-speak-translate
21+
***
22+
Use this command to translate English text.
23+
24+
25+
#### Base Command
26+
27+
`yoda-speak-translate`
28+
#### Input
29+
30+
| **Argument Name** | **Description** | **Required** |
31+
| --- | --- | --- |
32+
| text | The English text to translate. | Required |
33+
34+
35+
#### Context Output
36+
37+
| **Path** | **Type** | **Description** |
38+
| --- | --- | --- |
39+
| YodaSpeak.Translation | String | The translated text, in Yodish. |
40+
| YodaSpeak.Original | String | The original \(English\) text we translated. |
41+
42+
43+
#### Command Example
44+
``` !yoda-speak-translate text="this is some sentence for translation."```
45+
46+
#### Human Readable Output
47+
48+
### Yoda Says...
49+
|Original|Translation|
50+
|---|---|
51+
| this is some sentence for translation. | Some sentence for translation, this is. |
52+
Lines changed: 103 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,103 @@
1+
# uncomment the import statements for debugging in PyCharm, VS Code or other IDEs.
2+
# import demistomock as demisto
3+
# from CommonServerPython import * # noqa # pylint: disable=unused-wildcard-import
4+
# from CommonServerUserPython import * # noqa
5+
6+
TRANSLATE_OUTPUT_PREFIX = 'Phrase'
7+
8+
# Disable insecure warnings
9+
requests.packages.urllib3.disable_warnings() # pylint: disable=no-member
10+
11+
12+
class Client(BaseClient):
13+
def __init__(self, api_key: str, base_url: str, proxy: bool, verify: bool):
14+
super().__init__(base_url=base_url, proxy=proxy, verify=verify)
15+
self.api_key = api_key
16+
17+
if self.api_key:
18+
self._headers = {'X-Funtranslations-Api-Secret': self.api_key}
19+
20+
def translate(self, text: str):
21+
return self._http_request(method='POST', url_suffix='yoda', data={'text': text}, resp_type='json',
22+
ok_codes=(200,))
23+
24+
25+
def test_module(client: Client) -> str:
26+
"""
27+
Tests API connectivity and authentication'
28+
29+
Returning 'ok' indicates that connection to the service is successful.
30+
Raises exceptions if something goes wrong.
31+
"""
32+
33+
try:
34+
response = client.translate('I have the high ground!')
35+
36+
success = demisto.get(response, 'success.total') # Safe access to response['success']['total']
37+
if success != 1:
38+
return f'Unexpected result from the service: success={success} (expected success=1)'
39+
40+
return 'ok'
41+
42+
except Exception as e:
43+
exception_text = str(e).lower()
44+
if 'forbidden' in exception_text or 'authorization' in exception_text:
45+
return 'Authorization Error: make sure API Key is correctly set'
46+
else:
47+
raise e
48+
49+
50+
def translate_command(client: Client, text: str) -> CommandResults:
51+
if not text:
52+
raise DemistoException('the text argument cannot be empty.')
53+
54+
response = client.translate(text)
55+
translated = demisto.get(response, 'contents.translated')
56+
57+
if translated is None:
58+
raise DemistoException('Translation failed: the response from server did not include `translated`.',
59+
res=response)
60+
61+
output = {'Original': text, 'Translation': translated}
62+
63+
return CommandResults(outputs_prefix='YodaSpeak',
64+
outputs_key_field=f'{TRANSLATE_OUTPUT_PREFIX}.Original',
65+
outputs={TRANSLATE_OUTPUT_PREFIX: output},
66+
raw_response=response,
67+
readable_output=tableToMarkdown(name='Yoda Says...', t=output))
68+
69+
70+
def main() -> None:
71+
params = demisto.params()
72+
args = demisto.args()
73+
command = demisto.command()
74+
75+
api_key = params.get('apikey', {}).get('password')
76+
base_url = params.get('url', '')
77+
verify = not params.get('insecure', False)
78+
proxy = params.get('proxy', False)
79+
80+
demisto.debug(f'Command being called is {command}')
81+
try:
82+
client = Client(api_key=api_key, base_url=base_url, verify=verify, proxy=proxy)
83+
84+
if command == 'test-module':
85+
# This is the call made when clicking the integration Test button.
86+
return_results(test_module(client))
87+
88+
elif command == 'yoda-speak-translate':
89+
return_results(translate_command(client, **args))
90+
91+
else:
92+
raise NotImplementedError(f"command {command} is not implemented.")
93+
94+
# Log exceptions and return errors
95+
except Exception as e:
96+
demisto.error(traceback.format_exc()) # print the traceback
97+
return_error("\n".join(("Failed to execute {command} command.",
98+
"Error:",
99+
str(e))))
100+
101+
102+
if __name__ in ('__main__', '__builtin__', 'builtins'):
103+
main()
Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
category: Endpoint
2+
commonfields:
3+
id: YodaSpeak
4+
version: -1
5+
configuration:
6+
- defaultvalue: https://api.funtranslations.com/translate/
7+
display: Base URL of the service
8+
name: url
9+
required: true
10+
type: 0
11+
- displaypassword: API Key
12+
additionalinfo: The API Key to use for connection
13+
name: credentials
14+
required: false
15+
hiddenusername: true
16+
type: 9
17+
- display: Trust any certificate (not secure)
18+
name: insecure
19+
required: false
20+
type: 8
21+
- display: Use system proxy settings
22+
name: proxy
23+
required: false
24+
type: 8
25+
description: An integration to translate English to Yodish.
26+
display: YodaSpeak
27+
name: YodaSpeak
28+
script:
29+
commands:
30+
- arguments:
31+
- default: false
32+
description: The English text to translate
33+
isArray: false
34+
name: text
35+
required: true
36+
secret: false
37+
deprecated: false
38+
description: Use this command to translate English text.
39+
execution: false
40+
name: yoda-speak-translate
41+
outputs:
42+
- contextPath: YodaSpeak.Phrase.Translation
43+
description: The translated text, in Yodish.
44+
type: String
45+
- contextPath: YodaSpeak.Phrase.Original
46+
description: The original (English) text we translated.
47+
type: String
48+
isfetch: false
49+
runonce: false
50+
script: '-'
51+
type: python
52+
subtype: python3
53+
dockerimage: demisto/python3:3.9.9.25564
54+
fromversion: 6.0.0
55+
tests:
56+
- No tests (auto formatted)
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
## YodaSpeak Help section.
2+
3+
Markdown file for integration configuration help snippet.
4+
- To get an API key (for making more than 5 API calls per hour), visit the [FunTranslations subscription details page](https://funtranslations.com/api/yoda#subscribe)

0 commit comments

Comments
 (0)