Getting Started 1: Markdown – Simple formatting for your documents

This will be the first post of a series where I teach frontend developement. This series will include everything you need to know, sufficient to get you started with the basic tools that can help you create your site.

All web pages have formatted structure and content. Markdown exposes the most commonly used structures in web documents, so you can produce web documents without any knowledge of HTML.

Markdown is a widely adopted tool, and can be used to write your posts on WordPress and Tumblr, among other places. It is great place to start gaining more control over your content.

Trying it out

You can try Markdown using a web markdown editor, such as dillinger.io. But for those with more time on their hands, you can download the official markdown compiler to generate your web document (instructions here).

Basic markdown syntax

Here are a few basic formatting that you will be using very often in your documents.

# H1 Header: Title of the document
## H2 Header: Subtitle of the document
### H3 Header: Sub-subtitle of the document
#### H4 Header: It goes all the way to H6, so…
Do remember the space after the hashes

– Unordered list item1
* Unordered list item2
+ Unordered list item3
Yep, you can use either "-", "*" or "+"

1. Ordered list item1
2. Ordered list item2
5. Ordered list item3
It doesn't matter the order of items, they will all appear in the same list.

**Bold Text**
__This is bold text too__
These will be surround by <strong> tags (more on that in the next tutorials).

*Italics Text*
_This works too_
Surrounded in <em> tags, it means emphasised text (we'll cover that later too).

> quoteblock
> > Yep, quoteblocks can be nested
Quoteblocks are separated blocks of text that can be styled different from the rest of the text.

`inline code`
“ If you want to put "`" in your code, this is the way to go. Do note the space after the double backticks. “


***
Horizontal rule (one line across the document), both works

Links and Images

Links and images can be written differently, either inline or referenced.

Inline format for links
[Link Text](Link URL)
[Google](http://www.google.com)

Inline format for images
![Alt text for image](Link to image)
![Example Image](http://path/to/image.jpg)

Reference style format
[Google][1]
[1]: http://www.google.com (optional title)

Self referring format
[Google][]
[google]: http://www.google.com (name not case sensitive)

The references can be placed anywhere in the document, after the paragraph they are used, or at the end of the document, like footnotes.

Where to go after this

Markdown is just a basic formatting for your documents. All these are compiled into HTML(hyper-text markup language) which when viewed in browsers, comes will all the appropriate styling.

In the next tutorial, we will delve deeper into HTML itself, which gives you a better understandin of the HTML file that Markdown outputs.

I want more

There are many different markup languages, geared towards different usages. Personally, I would recommend you to learn and master GitHub Flavoured Markdown. It is one of the few widely adopted extension for markdown and can be used in many blogging and content creation platforms (dillinger supports GFM too).

The extended Github Flavoured Markdown includes many syntax to format more complex document structures like tables, code blocks, and many more.

Fountain is a markup language specially designed for writing scripts for plays. There are many different formatting for standard elements in plays, such as the setting, dialog, etc.

There are more of course, so, go forth and explore them on your own.

Advertisements

Telegram Tutorial – Simple Quote Bot

Introduction

Of all the APIs I have used, telegram’s API is one of the easiest to use. Mainly because of a few features they have put on place during the designing of the API.

  • Simplified creation process Requires little effort to create a bot
  • Simplified access to functions Emphasis placed on the main functions (receiving and sending messages)
  • Simple authentication scheme Just attach your telegram token to the telegram url

Here, I will teach you how to use the telegram API. After which, you will learn to develop a simple telegram bot that will provide random quotes when prompted.

Modules used

We will send random quotes from the python poem to the user when the user sends a /get message to the bot.

Requests is a library that allows you to send web requests, we will be using it to communicate with the telegram server, getting and sending message. You can install it using pip: pip install requests

Setting up a bot

It is fairly easy to create a bot in telegram. All the functions for the bot is housed under @BotFather. All bot related setup will go through there.

  • Start a conversation with @BotFather
  • Add a new bot using /newbot
  • It will request for a name. Choose a name that ends with bot
  • Record down the token somewhere, we will have use for it later

Getting updates

There are 2 ways of receiving messages from telegram – passively, through a web hook, and actively, through long polling.

In this tutorial, you will learn to actively receive updates through long polling. This does not require any type of hosting, its quick and easy to setup.

Long polling

The idea of long polling is to repeatedly sent requests to the server, making it appear as though a constant socket connection is sustained.

In the backend, this would mean having a loop that keeps sending out request for updates, it would be structured in the following manner.

import requests

offset = ''
timeout = '30'
while True:
    url = 'https://api.telegram.org/bot%s/getUpdates?offset=%s&amp;amp;amp;amp;amp;timeout=%s'%(token, offset, timeout)
    res  = requests.get(url).json()

    # Whatever you want to do to the update
    items = res['updates']

    for item in res:
        some_function(item)

    offest = items[-1]['offset']

This piece of code constantly retrieves data form the telegram server, updating the offset variable each time, we can tell the telegram server to ignore the messages we have recieved.

The timeout parameter tells the server to only return the request after a certain number of seconds. This is to prevent making too many requests to the server. But do take note, the longer your timeout period, the more “laggy” your bot will seem to be.

Sending messages

Your bot can provide help and confirmation by sending messages to your users. This is your only form of communication, so keep your messages succinct and helpful.

The url to send message from telegram is https://api.telegram.org/bot/sendMessage. These are the few paramters to include:

  • text: The message that you want to send
  • chat_id: The chat to send the message to

Sending as a reply

To attach the message as a reply, include the following paramter:

  • reply_to_message: The message that you want to attach to the reply

This can be obtained from the message information: item['message']['message_id']. It would appear to your users in the following manner.

Styling your replies

There is a simple styling syntax that you can use to prettify your messages. You can activate that mode by attaching the following parameters.

  • parse_mode: Set to Markdown to enable markdown parsing

The syntax is as follows:

*bold text*
_italics text_
`code`

Designing the commands

Format the message in the following format:
[function] - short description for the function

Example:
get - get random quote from server

Setting the commands

Go to BotFather and use the /setCommands, choose the bot you want to add the commands to, then paste in the following text: get get random quote from server.

Putting everything together

Setting up

Search for your desired bot name, make sure it doesn’t exist.

Go to BotFather, create your bot using /createBot, enter your bot name, BotFather will then give you the telegram API token, save that somewhere.

If you somehow forgot where you put your token, use the /getToken(too:check func) and BotFather will send it to you again.

Creating the server in python

The server is basically a script that will constantly get updates from telegram server then send out response messages and give people their quotes.

import requests
import this

### generate quotes from the python poem
quotes = []
for line in this.s.split('\n')[2:]:
    res = ''
    for char in line:
        res += this.d.get(char) or char
    quotes.append(res)

telegram_tkn = ''
telegram_url = 'https://api.telegram.org/bot%s/'%telegram_tkn
telegram_off = '' # offset for getting updates
telegram_out = '30' # 30 seconds of timeout

def parse(item):
    msg = item['message']
    chat_id = msg['chat']['id']
    txt = msg['text'] 

    res = 'Hey! I have no idea what you are doing, use `/get` to get random quotes.'
    if txt=='/get':
        res = quotes[random.randint(0, len(quotes))]
    if txt=='/start':
        res = 'Use `/get` to start getting random quotes'

    res = requests.get(telegram_url+'sendMessage', params=dict(
        parse_mode = 'Markdown',
        chat_id = chat_id,
        text = res,
    ))

while True:
    res = requests.get(telegram_url+'getUpdates', params=dict(
        timeout=telegram_out,
        offset=off
    ))
    items = res.json()['items']

    for item in items:
        parse(item)

    ### set the new offset
    telegram_off = items[-1]['id']

Testing the bot

From your telegram account, add your bot and start your server(python main.py). Send /get to the bot, and watch it sends you a random quote from the python poem.

Any problem, just comment below.

Revision plugin for later

Later is an issue tracker that I covered a week ago. Most issues trackers are able to track revisions (a feature later lacks). So I implemented one.

This little project is not too hard, the functions were fairly easy to implement. It was a great practice for writing maintainable code (eg. code refactoring, etc). Along the way, I made some changes to the way the main program works (auto loading of plugins, using of a main config file, etc).

Revision plugin for later

It was a good start and will be useful when I move into creating another interactive web backend plugin which allows users to use later more easily. I am planning to use web.py for that. I actually hoped to use this chance to learn some flask, but since it needs to be embedded, web.py would be more suitable.

Source code available on gitHub

Bug Tracking System: later

Now where is a bug tracker that is as easy and unobtrusive as my little git tool? Command-line usage already weeds out all the web-based solutions like Bugzilla, Trac, FogBugz, or Mantis. Likewise hosted solutions.

There are a few distributed bug tracker out there, of all, I have tried ditz and DITrack. I couldn’t get them to work well for me.

DITrack requires SVN repository, but I prefer something that is not tied down any revision control system. Plus, I prefer git and hg anyway.

After some Googling, I found later, with its accompanied blog post.

later is an open project, and its written in python, which means that I can very easily add features and make changes. Plus, the software design supports the development of plugins. (Game won, hands down)

After looking through the source code, I have made some minor changes in this fork. I have made some changes to personalize the program.

I am duely impressed by the design of the software. The use of _HOOKS to orgainize and add plugins is really smart. But there is some things I find lacking or problematic:
– Interactive web server (planning to use web.py for this)
– Use of uuid for identification (I prefer use of numbers instead, eg. #1, #898)

Since I am going to work through mobile, I am planning a telegram bot (maybe) that is somewhat like chatterbug, making use of online chat system to make simple changes to my .later files.