> ## Documentation Index
> Fetch the complete documentation index at: https://developers.strawberryfoundations.org/llms.txt
> Use this file to discover all available pages before exploring further.

# Usage

> How to use SCAPI

# Getting scapi

Our main scapi file can be found [here](https://raw.githubusercontent.com/Strawberry-Foundations/strawberry-chat/main/bot/scapi.py).
Simply place this file in the folder where you want to program your bot. You can find out how to use scapi in your code below.

We also recommend that you take a look at our [scapi bot directory](https://github.com/Strawberry-Foundations/strawberry-chat/tree/main/bot) to get an overview of how a bot can be structured.

# Using scapi in your code

Scapi gets easier with every update. To import Scapi, use Python's `import` statement:

```python theme={null}
import scapi            # import basic scapi
from scapi import Scapi # import the scapi bot class
```

<Tip>We recommend using YAML for configuration files. You can install YAML using `pip` (`pip install pyyaml`)</Tip>

# Write your first bot ([stbmv1](/stbchat/stbm))

<Warning>This documentation section only applies to Scapi Legacy v1.0.0 (stbmv1) or higher</Warning>

### First steps

To set up the basics of your bot, you need a bot object. You can create this using our bot object class:

```python theme={null}
Bot = Scapi.Bot(username="username", token="bottoken", host="1.2.3.4", port=1234)
```

In this table you can see all available arguments with their meaning

| Flag                | Erklärung                                                                     |
| ------------------- | ----------------------------------------------------------------------------- |
| `username`          | The user name of the bot                                                      |
| `token`             | The token (password) of the bot                                               |
| `host`              | Remote server where the bot should connect to                                 |
| `port`              | The port of the remote server                                                 |
| `enable_user_input` | Activate message input within the console (Also available as a flag)          |
| `print_recv_msg`    | Output received messages to the bot logs (console) (Also available as a flag) |

In order for the bot to log in to the server, you need to add an important function

```python theme={null}
Bot.login()
```

### Flags

Flags are an important part of programming your Scapi bot.
You need flags to determine, for example, whether you want to see messages from users in your bot logs or whether you want to activate message input within the console.
The definition of your flags could look like this:

```python theme={null}
Bot.flag_handler(print_recv_msg=True, enable_user_input=True)
```

In this table you can see all available flags with their meaning

| Flag                | Explanation                                        |
| ------------------- | -------------------------------------------------- |
| `print_recv_msg`    | Output received messages to the bot logs (console) |
| `enable_user_input` | Activate message input within the console          |
| `log_msg`           | Change the format of the log messages              |

### Permissions

Another part of your bot are authorizations. These check whether the user who has executed a command also has the necessary authorizations.
You can also define who the bot owner is.
There is a function in Scapi that accepts user-defined values for authorization management. You can use this function to define the bot owner,
or create a custom list and then use it within commands.
The owner and a custom list can be defined as follows:

```python theme={null}
Bot.permission_handler(custom_list=["julian"], owner="julian")
```

### Commands (`@commands` Module)

In order for the bot to have a purpose, it needs commands. A simple command looks like this:

<Info>
  Scapi has 2 different methods to write a bot. One method is newer and cleaner but is not yet fully developed. This method is called `Commands`.
  This part explains how to write a command using the command module

  For the other method, you can check out [this](/scapi/usage#commands-original-method) documentation section
</Info>

```python theme={null}
@Bot.command(name="test", arg_count=1, required_permissions=Scapi.Bot.PermissionLevel.CUSTOM)
def test_command(username: str, args: list):
    Bot.send_message(f"""
        Username: {username}
        Args: {args}"""
        )
```

To clarify what is meant by what, here is a detailed explanation:

| Code                   | Explanation                                                                                                                                                                                                |
| ---------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `name`                 | Stands for the command name, which is then added to the registry. You can then call up the command using the prefix and then the name (e.g. `!test`)                                                       |
| `arg_count`            | Number of arguments that the command accepts and requires as a minimum. A lower number can also be specified and more arguments can still be accepted                                                      |
| `required_permissions` | Required authorization for the command. A value of the Scapi class must be transferred here. `Scapi.Bot.PermissionLevel.CUSTOM` for the custom list that you have defined [here](/scapi/usage#permissions) |
| `username`             | The user name of the user who executed the command                                                                                                                                                         |
| `args`                 | The arguments that were passed when the command was executed. Is saved in a list (`["first", "second", "third"]`)                                                                                          |
| `send_message(...)`    | Function to send a message                                                                                                                                                                                 |

### Commands (Original Method)

As you have learned [here](/scapi/usage#commands-commands-module), Scapi has 2 different methods to write a bot command.
This part shows you how to use the other method.

This one is a bit more difficult, but can be more customized. This method is still used for pure `on_message`
events to accept & process pure messages.

<Tip>We recommend using the Commands method as it has more features & support than the original method (e.g. permissions)</Tip>

```python theme={null}
def Commands():
    while True:
        try:
            message = Bot.recv_message(raw=True)
        
            if message.startswith("!hello"):
                Bot.send_message(f"Hello, world!")
                    
        except: 
            Bot.logger(
                f"{scapi.RED}An unknown exception occured{scapi.RESET}",
                type=Scapi.LogLevel.ERROR
                )

            break
```

### Events

There are certain events that the bot can call up when something specific happens. One of these events is called `on_ready`.
This event is called when you start the bot. You only have to pass the `on_ready` function as an argument to the `Bot.run()` function.

An `on_ready` event can look like this:

```python theme={null}
@Bot.event
def on_ready():
    Bot.logger(
            f"{scapi.BLUE}{Bot.username} started successfully!{scapi.RESET}",
            type=Scapi.LogLevel.INFO
            )
```

### Start the bot

To start the bot, you first need to know which command method you are using.

<CodeGroup>
  ```python @commands theme={null}
  Bot.run(on_ready)
  ```

  ```python Original Method theme={null}
  BotThread = threading.Thread(target=Bot.run, args=(on_ready,))
  CommandThread = threading.Thread(target=Commands)

  BotThread.start()
  CommandThread.start()
  ```
</CodeGroup>

### Example bot (Stable v1.0)

<Warning>This example bot only applies to scapi legacy v1.0.0 (stbmv1)</Warning>

The other method is the original. This is more difficult, but can be adapted considerably more. This method is still used for pure `on_message` events to accept and process pure messages.
This method is called `Original`

<Tip>We recommend using the command method as it offers more features & more support than the original method (e.g. permissions)</Tip>

<CodeGroup>
  ```python Commands Method theme={null}
  import scapi                # This will import scapi
  from scapi import Scapi

  import yaml                 # Import yaml for configuration purposes
  from yaml import SafeLoader

  with open("default.yml", encoding="utf-8") as config_file:
      config = yaml.load(config_file, Loader=SafeLoader) # Load the configuration

  # Define some important variables
  username    = config["bot"]["username"]     
  token       = config["bot"]["token"]
  host        = config["server"]["host"]
  port        = config["server"]["port"]
  prefix      = config["bot"]["prefix"]

  Bot = Scapi.Bot(username=username, token=token, host=host, port=port) # Define the bot class
  Bot.login() # Login
  Bot.flag_handler(print_recv_msg=True, enable_user_input=True) # set some bot flags

  Bot.permission_handler(custom_list=["your_name"], owner="your_name") # manage your bot permissions

  # Basic bot command
  @Bot.command(name="test", arg_count=1, required_permissions=Scapi.Bot.PermissionLevel.CUSTOM)
  def test_command(username: str, args: list):
      Bot.send_message(f"""
          Username: {username}
          Args: {args}"""
          )

  # bot on_ready event
  @Bot.event
  def on_ready():
      print(f"{Bot.log_msg}{scapi.BLUE}{Bot.username} started successfully!{scapi.RESET}")

  # run the bot
  Bot.run(on_ready)
  ```

  ```python Original Method theme={null}
  import scapi
  from scapi import Scapi

  import yaml
  from yaml import SafeLoader
  import threading

  with open("default.yml", encoding="utf-8") as config:
      conf = yaml.load(config, Loader=SafeLoader)

  username    = conf["bot"]["username"]
  token       = conf["bot"]["token"]
  host        = conf["server"]["host"]
  port        = conf["server"]["port"]
  prefix      = conf["bot"]["prefix"]

  Bot = Scapi.Bot(username=username, token=token, host=host, port=port)
  Bot.login()
  Bot.flag_handler(print_recv_msg=True, enable_user_input=True)


  def Commands():
      while True:
          try:
              message = Bot.recv_message(raw=True)
          
              if message.startswith("!hello"):
                  Bot.send_message(f"Hello, world!")
                      
          except: 
              Bot.logger(f"{scapi.RED}An unknown exception occured{scapi.RESET}", type=Scapi.LogLevel.ERROR)
              break


  @Bot.event
  def on_ready():
      print(f"{Bot.log_msg}{scapi.BLUE}{Bot.username} started successfully!{scapi.RESET}")
      
  BotThread = threading.Thread(target=Bot.run, args=(on_ready,))
  CommandThread = threading.Thread(target=Commands)

  BotThread.start()
  CommandThread.start()
  ```
</CodeGroup>

This is an example of what your configuration could look like (YAML)

```yaml theme={null}
bot:
  id: 12345678
  username: "username"
  token: "token"
  prefix: "!"

server:
  host: "1.2.3.4"
  port: 1234

flags:
  enableUserInput: true
  printReceivedMessagesToTerminal: true
```

***

# Write your first bot ([stbmv2](/german/stbchat/stbm))

<Warning>This documentation section only applies to Scapi v0.12.0 (stbmv2) or higher</Warning>

### First steps

To set up the basics of your bot, you need a bot object. You can create this using our bot object class:

```python theme={null}
Bot = Scapi.Bot(username="username", token="bottoken", host="1.2.3.4", port=1234)
```

In this table you can see all available arguments with their meaning

| Flag                | Erklärung                                                                     |
| ------------------- | ----------------------------------------------------------------------------- |
| `username`          | The user name of the bot                                                      |
| `token`             | The token (password) of the bot                                               |
| `host`              | Remote server where the bot should connect to                                 |
| `prefix`            | The prefix of the bot to which it should listen (e.g. `!help`)                |
| `port`              | The port of the remote server                                                 |
| `enable_user_input` | Activate message input within the console (Also available as a flag)          |
| `print_recv_msg`    | Output received messages to the bot logs (console) (Also available as a flag) |
| `json`              | Activates or deactivates the compatibility mode for old servers               |

<Warning>The argument `json` is only available since Scapi v0.12.1</Warning>
<Warning>The argument `prefix` is only available since Scapi v0.13.1b2</Warning>

In order for the bot to log into the server, you need to add an important function

```python theme={null}
Bot.login()
```

### Flags

Flags are an important part of programming your Scapi bot.
You need flags to determine, for example, whether you want to see messages from users in your bot logs or whether you want to activate message input within the console.
The definition of your flags could look like this:

```python theme={null}
Bot.flag_handler(print_recv_msg=True, enable_user_input=True)
```

In this table you can see all available flags with their meaning

| Flag                    | Explanation                                                                                                                |
| ----------------------- | -------------------------------------------------------------------------------------------------------------------------- |
| `print_recv_msg`        | Output received messages to the bot logs (console)                                                                         |
| `enable_user_input`     | Activate message input within the console                                                                                  |
| `log_msg`               | Change the format of the log messages                                                                                      |
| `ignore_capitalization` | Activates or deactivates the ignoring of capital letters for the `on_message` method (**only available from Scapi v0.13**) |

### Permissions

Another part of your bot are authorizations. These check whether the user who has executed a command also has the necessary authorizations.
You can also define who the bot owner is.
There is a function in Scapi that accepts user-defined values for authorization management. You can use this function to define the bot owner,
or create a custom list and then use it within commands.
The owner and a custom list can be defined as follows:

```python theme={null}
Bot.permission_handler(custom_list=["julian"], owner="julian")
```

### Commands (Commands Module)

In order for the bot to have a purpose, it needs commands. A simple command looks like this:

<Info>
  Scapi has 2 different methods to write a bot. One method is newer and cleaner but is not yet fully developed. This method is called `Commands`.
  This part explains how to write a command using the command module.

  The older method is deprecated since Scapi v0.12.1 and should therefore no longer be used
</Info>

```python theme={null}
@Bot.command(name="test", arg_count=1, required_permissions=Scapi.Bot.PermissionLevel.CUSTOM)
def test_command(username: str, args: list):
    Bot.send_message(f"""
        Username: {username}
        Args: {args}"""
        )
```

To clarify what is meant by what, here is a detailed explanation:

| Code                   | Explanation                                                                                                                                                                                                  |
| ---------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `name`                 | Stands for the command name, which is then added to the registry. You can then call up the command using the prefix and then the name (e.g. `!test`)                                                         |
| `arg_count`            | Number of arguments that the command accepts and requires as a minimum. A lower number can also be specified and more arguments can still be accepted                                                        |
| `required_permissions` | Required authorization for the command. A value of the Scapi class must be transferred here. `Scapi.Bot.PermissionLevel.CUSTOM` for the custom list that you have defined [here](/scapi/usage#permissions-2) |
| `username`             | The user name of the user who executed the command                                                                                                                                                           |
| `args`                 | The arguments that were passed when the command was executed. Is saved in a list (`["first", "second", "third"]`)                                                                                            |
| `send_message(...)`    | Function to send a message                                                                                                                                                                                   |

You can find more commands here

<AccordionGroup>
  <Accordion title="Direct messages" icon="message" iconType="duotone">
    ```python theme={null}
    @Bot.command(name="dm", arg_count=1)
    def send_dm_command(username: str, args: list):
        Bot.send_direct_message(username, " ".join(args))
    ```
  </Accordion>

  <Accordion title="Leave the chat" icon="door-open" iconType="duotone">
    ```python theme={null}
    @Bot.command(name="exit",
                required_permissions=Scapi.Bot.PermissionLevel.OWNER)
    def exit_command(username: str, args: list):
        Bot.exit()
    ```
  </Accordion>
</AccordionGroup>

### Commands (Original Method)

<Warning>
  The official support for the [original method](/scapi/usage#commands-original-method) has been removed since Scapi v0.12.1.

  To continue using the original method, we recommend the new `@on_message` method (since v0.13). If functionality is missing, please open an [Issue](https://github.com/Strawberry-Foundations/strawberry-chat/issues) on our [GitHub](https://github.com/Strawberry-Foundations/strawberry-chat/)

  If you still want to use this method for whatever reason, please have a look at [this](/scapi/usage#commands-original-method) part of the documentation
</Warning>

### Events

There are certain events that the bot can call up when something specific happens.

#### @on\_message Event

As of Scapi v0.13, we have added an improved version of the original message method. This uses our modern Python standard and Python decorators.
The implementation in your bot code is very simple. You only need at least Scapi v0.13 or higher.
A bot message event can look like this:

```python theme={null}
# Python decorator to define the message event
@Bot.on_message(message="Hello")
# Definition of the function in order to execute it automatically afterwards
def on_hello_message(username: str): 
    # The code of the function, e.g what is to be executed [...]
    Bot.send_message(f"Hello {username}!") 
```

<Warning>
  Not all functions of the old original method could be adopted, therefore the `@on_message` method is more restricted.

  The following functions could not be implemented so far (but could appear in a different form in the future):

  * Use of .startswith()
  * Recognizing specific words within the message

  **This feature is currently only used, for example, to process a normal word from a user and reply to it.**
</Warning>

#### @on\_ready Event

This event is called when you start the bot. You only have to pass the `on_ready` function as an argument to the `Bot.run()` function.
An `on_ready` event can look like this:

```python theme={null}
@Bot.event
def on_ready():
    Bot.logger(
            f"{scapi.BLUE}{Bot.username} started successfully!{scapi.RESET}",
            type=Scapi.LogLevel.INFO
            )
```

### Start the bot

To start the bot, you first need to know which command method you are using.

<CodeGroup>
  ```python @commands theme={null}
  Bot.run(on_ready)
  ```

  ```python Original Method theme={null}
  BotThread = threading.Thread(target=Bot.run, args=(on_ready,))
  CommandThread = threading.Thread(target=Commands)

  BotThread.start()
  CommandThread.start()
  ```
</CodeGroup>

### Example bot (v0.12.0 or higher)

<Warning>This documentation part only applies to scapi v0.12.0 (stbmv2) or higher</Warning>

<Warning>
  Official support for the [original method](/scapi/usage#commands-original-method) has been removed since Scapi v0.12.1.
  You can read more about it [here](/scapi/usage#commands-original-method-2)
</Warning>

You can get Scapi (`@json-communication`/`@main`) [here](https://raw.githubusercontent.com/Strawberry-Foundations/strawberry-chat/main/bot/scapi.py).
The following piece of code shows you how to make a simple bot with Scapi (stbmv2)

<CodeGroup>
  ```python @commands theme={null}
  import scapi
  from scapi import Scapi

  import yaml
  from yaml import SafeLoader

  with open("default.yml", encoding="utf-8") as config_file:
      config = yaml.load(config_file, Loader=SafeLoader)

  username    = config["bot"]["username"]
  token       = config["bot"]["token"]
  host        = config["server"]["host"]
  port        = config["server"]["port"]
  prefix      = config["bot"]["prefix"]

  Bot = Scapi.Bot(username=username, token=token, host=host, port=port, json=True)
  Bot.login()
  Bot.flag_handler(print_recv_msg=True, enable_user_input=True)

  Bot.permission_handler(custom_list=["julian"], owner="julian")

  @Bot.command(name="test", arg_count=1, required_permissions=Scapi.Bot.PermissionLevel.CUSTOM)
  def test_command(username: str, args: list):
      Bot.send_message(f"""
          Username: {username}
          Args: {args}"""
          )

  @Bot.event
  def on_ready():
      Bot.logger(f"{scapi.BLUE}{Bot.username} started successfully!{scapi.RESET}", type=Scapi.LogLevel.INFO)
      
  Bot.run(on_ready)
  ```

  ```python @commands + @on_message (since v0.13) theme={null}
  import scapi
  from scapi import Scapi

  import yaml
  from yaml import SafeLoader

  with open("default.yml", encoding="utf-8") as config_file:
      config = yaml.load(config_file, Loader=SafeLoader)

  username    = config["bot"]["username"]
  token       = config["bot"]["token"]
  host        = config["server"]["host"]
  port        = config["server"]["port"]
  prefix      = config["bot"]["prefix"]

  Bot = Scapi.Bot(username=username, token=token, host=host, port=port, json=True)
  Bot.login()
  Bot.flag_handler(print_recv_msg=True, enable_user_input=True)

  Bot.permission_handler(custom_list=["julian"], owner="julian")

  # New on_message method to process plain messages from the user
  @Bot.on_message(message="Hello")
  def on_hello_message(username: str):
      Bot.send_message(f"Hello {username}!")

  @Bot.command(name="test", arg_count=1, required_permissions=Scapi.Bot.PermissionLevel.CUSTOM)
  def test_command(username: str, args: list):
      Bot.send_message(f"""
          Username: {username}
          Args: {args}"""
          )

  @Bot.event
  def on_ready():
      Bot.logger(f"{scapi.BLUE}{Bot.username} started successfully!{scapi.RESET}", type=Scapi.LogLevel.INFO)
      
  Bot.run(on_ready)
  ```

  ```python Original Method (Deprecated since v0.12.1) theme={null}
  # WARNING: This method is deprecated
  # WE WILL WORK ON A BETTER VERSION OF THIS METHOD

  import scapi
  from scapi import Scapi

  import yaml
  from yaml import SafeLoader
  import threading

  with open("default.yml", encoding="utf-8") as config:
      conf = yaml.load(config, Loader=SafeLoader)

  username    = conf["bot"]["username"]
  token       = conf["bot"]["token"]
  host        = conf["server"]["host"]
  port        = conf["server"]["port"]
  prefix      = conf["bot"]["prefix"]

  Bot = Scapi.Bot(username=username, token=token, host=host, port=port)
  Bot.login()
  Bot.flag_handler(print_recv_msg=True, enable_user_input=True)


  def Commands():
      while True:
          try:
              message = Bot.recv_message(raw=True)
          
              if message.startswith("!hello"):
                  Bot.send_message(f"Hello, world!")
                      
          except: 
              Bot.logger(f"{scapi.RED}An unknown exception occured{scapi.RESET}", type=Scapi.LogLevel.ERROR)
              break


  @Bot.event
  def on_ready():
      print(f"{Bot.log_msg}{scapi.BLUE}{Bot.username} started successfully!{scapi.RESET}")
      
  BotThread = threading.Thread(target=Bot.run, args=(on_ready,))
  CommandThread = threading.Thread(target=Commands)

  BotThread.start()
  CommandThread.start()
  ```
</CodeGroup>

Changing the value `json` to `False` will enable the compatibility mode. Note that this is not yet fully developed
