Skip to content

Documentation

AWeirdDev edited this page Feb 5, 2023 · 29 revisions

Table Of Contents

Just skip to the part where you want to get started.

Topic Description
Client Represents a LINE Official Acc...
linelib.ext Extensions for building your bot.

Client

class Client(
    self,
    channel_secret: str,
    channel_access_token: str,
    *args, **options: Any
)

Represents a LINE Official Account (Client).

Client - Parameters

parameter type default description
channel_secret str required Channel secret.
channel_access_token str required Channel access token.
*args, **options Any (), {} No usage provided.

Client - Example

from linelib import Client

client = Client('channel secret', 'channel access token')

Client - Attributes

  • CS : str - Channel secret.
  • CAT : str - Channel access token.
  • app : Flask - (Running) Flask application. Note that it has been used CORS(app)
  • headers : dict - Headers for requests.
  • loop : Loop- Asyncio event loop.
  • _EVENTS* : dict- Saved event handlers.
  • _VALID_EVENTS* : list - Current valid events.
📢 Notice!
* - These attributes should not be overwritten or deleted by the user.

Client - Methods

Client.createEvents

def createEvents(
    self,
    name: str,
    obj: type
) -> None

Save the provided content to Client._EVENTS.

Client.createEvents - Parameters

parameter type default description
name str required Event name.
obj type required An event object.

Client.createEvents - Example

from linelib import Client

client = Client(...)

class ControlledEventObject:
    def __init__(self, json: dict):
        self.type = json['type'] # event type, REQUIRED
        self.options = json['options'] # additional options, REQUIRED
    
    async def emit(self, ctx):
        await ctx.reply('Hello, World!')

obj = ControlledEventObject({
    'type': 'text', # text message event
    'options': () # Empty
})

client.createEvents('text', obj) # registers the event handler

Client.emitEvents

def emitEvents(
    self,
    name: str,
    *args: Any,
    **kwargs: Any
) -> None

Runs the events inside Client._EVENTS.

Client.emitEvents - Parameters

parameter type default description
name str required The event name.
*args, **kwargs Any (), {} Any arguments to add for the event handlers.

Client.emitEvents - Example

from linelib import Client

client = Client(...)

@client.event('ready')
async def execute_me():
    print("I just got executed!")

client.emitEvents('ready') # no arguments required

Client.event

@event(
    self,
    listener: str,
    *options
) -> EventObject

Registers an event handler. See Client._VALID_EVENTS to see a list of valid events.

Client.event - Parameters

Decorator Parameters

parameter type default description
listener Union[str, Callable] FUNCTION_NAME_OR_LISTENER Listener name or leave blank.
📖 Reference
FUNCTION_NAME_OR_LISTENER - You can pass in a valid function (Client._VALID_EVENTS), or you can leave this blank and let linelib detect your function name. (Prefix: on_ + Event name)

Handler Parameters

Handlers must be async (coroutine) functions.

parameter type description
ctx? None? Depends The specification depends on the event type.

Depends: ctx? None?

event name argument(s) type description
ready No arguments should be passed.
text ctx TextMessageEvent The text message context.
postback ctx PostbackEvent The postback context.
sticker ctx StickerMessageEvent The sticker message context.
unsend ctx UnsendEvent Message unsent. (Cannot reply)
follow ctx FollowEvent A user added your bot as friend or unblocked your bot.
unfollow ctx UnfollowEvent A user blocked your bot.
join ctx JoinEvent Occurs when your bot joins a group chat.
leave ctx LeaveEvent Occurs when your bot leaves a group chat.
memberJoined ctx MemberJoinEvent Occurs when a member joins the group chat.
memberLeft ctx MemberLeaveEvent Occurs when a member leaves the group chat.
videoPlayComplete ctx VideoViewingCompleteEvent The user finishes viewing a video for at least once.
beacon ctx BeaconEvent LINE beacon event (enter, stay, banner)
accountLink ctx AccountLinkEvent The user has linked their LINE account with a provider's service account.
image ctx ImageMessageEvent The image message context. You can download them.
video ctx VideoMessageEvent The video message context. You can download them.
audio ctx AudioMessageEvent The audio message context. You can download them.
file ctx FileMessageEvent The file message context. You can download them.
location ctx LocationMessageEvent The location event context.

Client.event - Example

from linelib import Client

client = Client(...)

# method 1
@client.event('ready')
async def ready(): # any name you want
    print("WOW!")

# method 2
@client.event()
async def on_ready(): # on_{EVENT_NAME}
    print("Wow, again -- wow!!")

@client.event('text')
async def on_text(ctx):
  await ctx.reply('Good morning!')

client.run(...)

Client.load_cog

def load_cog(
    self,
    cog: type
)

Loads a Cog (extension).

Client.load_cog - Parameters

parameter type default description
cog type required The cog to load.

Client.run

def run(
    self,
    *args,
    **options: Any
)

Runs the LINE bot.

Client.run - Parameters

parameter type default description
**options Any {} Configure run options. See Client Options →

⚙️ Client Options

option type description example
log_level level Sets the logger level of Flask. log_level=logging.ERROR
show_logs bool Show linelib logs? show_logs=False
* Any Unnamed for linelib, only for app.run options. threaded=True

Client.run - Example

from linelib import Client

client = Client(...)

client.run(log_level=logging.ERROR, show_logs=False, threaded=True)

linelib.ext

import linelib.ext

Extensions for building your bot.

SocialPlugins

class SocialPlugins

The LINE Social Plugins. (extension)

SocialPlugins.share

@staticmethod
def share(
  url: str
) -> str

Returns a LINE Share Link. This is useful when you want a custom button.

SocialPlugins.share - Example

from linelib.ext import SocialPlugins

print(SocialPlugins.share("https://example.com"))

Depends

constructed <_depends>: Depends

Represents something depends on the specification.

Depends - Methods

__bool__

def __bool__(self) -> bool

Returns False.

__repr__

def __repr__(self) -> str

Returns "It Depends."

__hash__

def __hash__(self) -> int

Returns 0.

__getitem__

def __getitem__(self, k) -> Any

Returns k.

Depends - Example

from linelib.ext import Depends

def my_function(arg: Depends[str] = None):
  pass

commands

from linelib.ext import commands

commands module.

commands.VALID_TYPES

VALID_TYPES: list[type]

An array of valid typings for cog command arguments.

commands.Cog

class Cog(self)

Represents a command cog.

The above represents an __init__ method, which is not recommended using until you've constructed with __init_subclass__.

📦 Properties →

⚙️ Methods →

Cog.__init_subclass__

def __init_subclass__(cls) -> None

Subclass initialization (highly recommended). This gathers valid linelib cog commands and store them into _ll_COMMANDS for further usage.

Example

from linelib.ext import commands

class MyCog(commands.Cog):
  ...

Cog.emit

async def emit(self, ctx: type) -> Depends[str]

Emits the commands inside the cog. (DO NOT TOUCH)

Returns "all-nf" (str) if every command name cannot satisfy the condition (command not found).

See Depends for typing →

Cog.not_found

async def not_found(self, ctx, command: str) -> Any

Emits when a command is not found. This coroutine function is overwritable.

Example

from linelib.ext import commands

class MyCog(commands.Cog):
  async def not_found(self, ctx, command):
    await ctx.reply(f"Command '{command}' not found.")

commands.Cog - Properties

properties default description
name "UnnamedCog" The name of the cog.
show_not_found_log False Whether to show command not found log or not.
_ll_CONSTRUCTED* False Identification to check if this cog is constructed when using Client.load_cog.
_ll_COMMANDS* [] Temporary list to store commands detected inside a cog class.
📢 Notice
*: Do not touch

commands.CogCommandWrapper

class CogCommandWrapper(
  self,
  cmd_name: str,
  func,
  rule: CommandRule | _dfr = DEFAULT_RULE
)

Represents a cog command.

CogCommandWrapper - Parameters

parameters type default description
cmd_name str required Command name.
func Callable required Handler function.
rule CommandRule | _dfr DEFAULT_RULE Command rules.

CogCommandWrapper.emit

async def emit(self, o: Cog, ctx: type) -> Depends[str]

Event emitting for the handler. Returns "no" (str) if this command does not equal to the context. (ctx.content)

DO NOT TOUCH

See Depends for typing →

CogCommandWrapper.emit - Parameters
parameters type default description
o Cog required The Cog itself.
ctx type required The context.

CogCommandWrapper.on_error

@on_error(
  self,
  function: Callable
)

Event decorator when an error occurs.

The handler must be an async (coroutine) function.

type parameters description
@decorator * You do not need to add anything.
handler self, ctx, error error: The error message.

Example

from linelib.ext import commands

class MyCog(commands.Cog):
  @commands.cog_command() # returns CogCommandWrapper
  async def my_command(self, ctx):
    ...

  @my_command.on_error
  async def my_error_handler(self, ctx, error):
    print(error)

CogCommandWrapper.rule_reject

@rule_reject(
  self,
  function: Callable
) -> Callable

Event decorator once the rule function returned False, which represents no pass.

The handler must be an async (coroutine) function.

type parameters description
@decorator * You do not need to add anything.
handler self, ctx The context.

Example

from linelib.ext import commands, rule

clas MyCog(commands.Cog):
  @commands.cog_command(
    name="hello",
    rule=rule.CommandRule(
      rule="cooldown",
      seconds=10
    )
  ) # returns CogCommandWrapper
  async def hello(self, ctx):
    ...

  @hello.rule_reject
  async def rejected(self, ctx):
    await ctx.reply("Rejected!")

commands.cog_command

@cog_command(
  *,
  name: String@CogCommandWrapper,
  rule: CommandRule = DEFAULT_RULE
) -> CogCommandWrapper

Represents a command for cogs.

@decorator parameters

parameter type default description example
* -- -- -- You need to use named keywords.
name String@CogCommandWrapper required The command name. name="hello"
rule CommandRule required Command rule. See CommandRule

Handler parameters

commands.String

constructed <_str>: String

Represents any string.

commands.String - Methods

def __matmul__(self, other) -> Any

Returns other.

commands.String - Example

from typing import Any
from linelib.ext import commands

commands.String@Any

Hello! I am a cute sidebar that makes you to read this whole text with no doubt.

I was born in 1969 and collaborated with Gustavo Fring for my entire life, and my motto is: "Life is a career."

Actually, I have a more important announcement to make besides my profile.

My name is Sustavo Fring, but you can call me Sus.

I am the secondary owner of Los Pollos Hermanos that almost nobody knows.

Gustavo and I created an empire.

I AM THE DANGER.

My name is Walter Hartwell White. I live at-

Clone this wiki locally