100% found this document useful (1 vote)
5 views

Building Telegram Bots: Develop Bots in 12 Programming Languages using the Telegram Bot API 1st Edition Nicolas Modrzyk pdf download

The document is a guide titled 'Building Telegram Bots' by Nicolas Modrzyk, which teaches readers how to develop bots using the Telegram Bot API across 12 different programming languages. It includes practical examples and step-by-step instructions for each language, covering installation and bot creation. The book is designed for developers looking to enhance their skills in bot development and artificial intelligence applications.

Uploaded by

ebesudorne0e
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
5 views

Building Telegram Bots: Develop Bots in 12 Programming Languages using the Telegram Bot API 1st Edition Nicolas Modrzyk pdf download

The document is a guide titled 'Building Telegram Bots' by Nicolas Modrzyk, which teaches readers how to develop bots using the Telegram Bot API across 12 different programming languages. It includes practical examples and step-by-step instructions for each language, covering installation and bot creation. The book is designed for developers looking to enhance their skills in bot development and artificial intelligence applications.

Uploaded by

ebesudorne0e
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 64

Building Telegram Bots: Develop Bots in 12

Programming Languages using the Telegram Bot API


1st Edition Nicolas Modrzyk download

https://textbookfull.com/product/building-telegram-bots-develop-
bots-in-12-programming-languages-using-the-telegram-bot-api-1st-
edition-nicolas-modrzyk/

Download more ebook from https://textbookfull.com


We believe these products will be a great fit for you. Click
the link to download now, or visit textbookfull.com
to discover even more!

Developing bots with Microsoft Bots Framework: create


intelligent bots using MS Bot Framework and Azure
Cognitive Services 1st Edition Srikanth Machiraju

https://textbookfull.com/product/developing-bots-with-microsoft-
bots-framework-create-intelligent-bots-using-ms-bot-framework-
and-azure-cognitive-services-1st-edition-srikanth-machiraju/

Introducing Azure Bot Service Building Bots for


Business Waghmare

https://textbookfull.com/product/introducing-azure-bot-service-
building-bots-for-business-waghmare/

Practical Bot Development: Designing and Building Bots


with Node.js and Microsoft Bot Framework Szymon Rozga

https://textbookfull.com/product/practical-bot-development-
designing-and-building-bots-with-node-js-and-microsoft-bot-
framework-szymon-rozga/

Building Bots with Microsoft Bot Framework Creating


intelligent conversational interfaces 1st Edition
Kishore Gaddam

https://textbookfull.com/product/building-bots-with-microsoft-
bot-framework-creating-intelligent-conversational-interfaces-1st-
edition-kishore-gaddam/
Designing Bots Creating Conversational Experiences 1st
Edition Amir Shevat

https://textbookfull.com/product/designing-bots-creating-
conversational-experiences-1st-edition-amir-shevat/

Practical Artificial Intelligence: Machine Learning,


Bots, and Agent Solutions Using C# 1st Edition Arnaldo
Pérez Castaño

https://textbookfull.com/product/practical-artificial-
intelligence-machine-learning-bots-and-agent-solutions-
using-c-1st-edition-arnaldo-perez-castano/

Java Image Processing Recipes: With OpenCV and JVM 1st


Edition Nicolas Modrzyk

https://textbookfull.com/product/java-image-processing-recipes-
with-opencv-and-jvm-1st-edition-nicolas-modrzyk/

Building Intelligent Cloud Applications Develop


Scalable Models Using Serverless Architectures with
Azure 1st Edition Vicente Herrera García

https://textbookfull.com/product/building-intelligent-cloud-
applications-develop-scalable-models-using-serverless-
architectures-with-azure-1st-edition-vicente-herrera-garcia/

Introduction to Deep Learning Business Applications for


Developers: From Conversational Bots in Customer
Service to Medical Image Processing Armando Vieira

https://textbookfull.com/product/introduction-to-deep-learning-
business-applications-for-developers-from-conversational-bots-in-
customer-service-to-medical-image-processing-armando-vieira/
Building
Telegram Bots
Develop Bots in 12 Programming
Languages using the Telegram
Bot API

Nicolas Modrzyk
Building Telegram
Bots
Develop Bots in
12 Programming Languages
using the Telegram Bot API

Nicolas Modrzyk
Building Telegram Bots: Develop Bots in 12 Programming Languages using
the Telegram Bot API
Nicolas Modrzyk
Tokyo, Tokyo, Japan

ISBN-13 (pbk): 978-1-4842-4196-7 ISBN-13 (electronic): 978-1-4842-4197-4


https://doi.org/10.1007/978-1-4842-4197-4
Library of Congress Control Number: 2018965498

Copyright © 2019 by Nicolas Modrzyk


This work is subject to copyright. All rights are reserved by the Publisher, whether the whole or
part of the material is concerned, specifically the rights of translation, reprinting, reuse of
illustrations, recitation, broadcasting, reproduction on microfilms or in any other physical way,
and transmission or information storage and retrieval, electronic adaptation, computer software,
or by similar or dissimilar methodology now known or hereafter developed.
Trademarked names, logos, and images may appear in this book. Rather than use a trademark
symbol with every occurrence of a trademarked name, logo, or image, we use the names, logos,
and images only in an editorial fashion and to the benefit of the trademark owner, with no
intention of infringement of the trademark.
The use in this publication of trade names, trademarks, service marks, and similar terms, even if
they are not identified as such, is not to be taken as an expression of opinion as to whether or not
they are subject to proprietary rights.
While the advice and information in this book are believed to be true and accurate at the date of
publication, neither the author nor the editors nor the publisher can accept any legal
responsibility for any errors or omissions that may be made. The publisher makes no warranty,
express or implied, with respect to the material contained herein.
Managing Director, Apress Media LLC: Welmoed Spahr
Acquisitions Editor: Nikhil Karkal
Development Editor: Matthew Moodie
Coordinating Editor: Divya Modi
Cover designed by eStudioCalamar
Cover image designed by Freepik (www.freepik.com)
Distributed to the book trade worldwide by Springer Science+Business Media New York,
233 Spring Street, 6th Floor, New York, NY 10013. Phone 1-800-SPRINGER, fax (201) 348-4505,
e-mail [email protected], or visit www.springeronline.com. Apress Media, LLC is a
California LLC and the sole member (owner) is Springer Science+Business Media Finance Inc
(SSBM Finance Inc). SSBM Finance Inc is a Delaware corporation.
For information on translations, please e-mail [email protected], or visit www.apress.com/
rights-permissions.
Apress titles may be purchased in bulk for academic, corporate, or promotional use. eBook
versions and licenses are also available for most titles. For more information, reference our Print
and eBook Bulk Sales web page at www.apress.com/bulk-sales.
Any source code or other supplementary material referenced by the author in this book is available
to readers on GitHub via the book’s product page, located at www.apress.com/978-1-4842-4196-7.
For more detailed information, please visit www.apress.com/source-code.
Printed on acid-free paper
Table of Contents
About the Author���������������������������������������������������������������������������������ix
About the Technical Reviewers�����������������������������������������������������������xi
Acknowledgments�����������������������������������������������������������������������������xiii
Introduction����������������������������������������������������������������������������������������xv

Chapter 1: Week 1: Ruby����������������������������������������������������������������������1


Chatting with the BotFather����������������������������������������������������������������������������������1
Setting Up Ruby����������������������������������������������������������������������������������������������������7
Your First Telegram Bot�����������������������������������������������������������������������������������������8
Understanding Received Messages Fields���������������������������������������������������������14
First Reply�����������������������������������������������������������������������������������������������������������15

Chapter 2: Week 2: Nim����������������������������������������������������������������������17


Installing Nim������������������������������������������������������������������������������������������������������17
Nim Plug-in for Visual Studio Code���������������������������������������������������������������������18
Hello, Nim������������������������������������������������������������������������������������������������������������20
Second Nim Program (Still Not Bot)��������������������������������������������������������������������23
Creating Visual Studio Code Build Tasks�������������������������������������������������������������25
Installing Nim Packages with Nimble�����������������������������������������������������������������29
First Nim Bot�������������������������������������������������������������������������������������������������������31
Replying to Nim Bot��������������������������������������������������������������������������������������������33
Cats and Dogs Nim Bot���������������������������������������������������������������������������������������34

iii
Table of Contents

Chapter 3: Week 3: Crystal�����������������������������������������������������������������37


Setting Up Crystal�����������������������������������������������������������������������������������������������38
Short Walk in the Playground������������������������������������������������������������������������������39
Going Visual Studio Code Again��������������������������������������������������������������������������41
Creating a Crystal Project�����������������������������������������������������������������������������������46
Echo Bot��������������������������������������������������������������������������������������������������������������50
Command Bot�����������������������������������������������������������������������������������������������������52

Chapter 4: Week 4: Rust���������������������������������������������������������������������57


Rust Installation and First Steps�������������������������������������������������������������������������58
Installation�����������������������������������������������������������������������������������������������������58
First Rust or Two�������������������������������������������������������������������������������������������������62
Hello Rust������������������������������������������������������������������������������������������������������62
Fibonacci�������������������������������������������������������������������������������������������������������64
Ride the cargo�����������������������������������������������������������������������������������������������������66
We Have Time������������������������������������������������������������������������������������������������66
Multiple Cargo Targets����������������������������������������������������������������������������������������70
Rust Bot Number 1: Reply to Me�������������������������������������������������������������������������74
Rust Bot Number 2: Where Is Tokyo?������������������������������������������������������������������77
Rust Bot Number 3: Chained Reaction����������������������������������������������������������������82
Compiling for Release�����������������������������������������������������������������������������������������84

Chapter 5: Week 5: D��������������������������������������������������������������������������85


Installation and First D Steps������������������������������������������������������������������������������86
Some Bits of D on Concurrency��������������������������������������������������������������������������91
Simple Threading�������������������������������������������������������������������������������������������91
Thread with a State���������������������������������������������������������������������������������������92
Shared State��������������������������������������������������������������������������������������������������94

iv
Table of Contents

A Few More Examples of D���������������������������������������������������������������������������������95


Sort Me Tender, Sort Me True�������������������������������������������������������������������������95
My Love for Fibonacci�����������������������������������������������������������������������������������98
Telegram Bots in D��������������������������������������������������������������������������������������������100
Meet dub�����������������������������������������������������������������������������������������������������������100
First D Bot����������������������������������������������������������������������������������������������������105
More Bot API Usage�������������������������������������������������������������������������������������107

Chapter 6: Week 6: C++��������������������������������������������������������������������111


Requirements, Installation, and First Bot����������������������������������������������������������111
Install tgbot-cpp������������������������������������������������������������������������������������������112
Install OpenCV���������������������������������������������������������������������������������������������113
File Download Program�������������������������������������������������������������������������������113
Echo Bot������������������������������������������������������������������������������������������������������������119
C++ Bots�����������������������������������������������������������������������������������������������������������123
Bot with Inline Keyboard�����������������������������������������������������������������������������123
Photo Bot�����������������������������������������������������������������������������������������������������126
OpenCV in action�����������������������������������������������������������������������������������������������128
OpenCV Sample Program����������������������������������������������������������������������������128
OpenCV Bot�������������������������������������������������������������������������������������������������������131

Chapter 7: Week 7: Clojure���������������������������������������������������������������135


Initial Setup and First Clojure Bot���������������������������������������������������������������������136
Visual Studio Code���������������������������������������������������������������������������������������141
The Project Metadata in project.clj��������������������������������������������������������������142
The Clojure Code in core.clj�������������������������������������������������������������������������143
The Token!���������������������������������������������������������������������������������������������������146
Debugging Telegram Messages�������������������������������������������������������������������146

v
Table of Contents

Creating a Reverse Bot��������������������������������������������������������������������������������148


Inline Handler����������������������������������������������������������������������������������������������149
A Simple Weather Bot���������������������������������������������������������������������������������������150
OpenCV and Telegram: Origami Bot������������������������������������������������������������������154

Chapter 8: Week 8: Java�������������������������������������������������������������������159


Installation��������������������������������������������������������������������������������������������������������159
The Project Structure����������������������������������������������������������������������������������161
The build.gradle file�������������������������������������������������������������������������������������161
Visual Studio Code Setup����������������������������������������������������������������������������164
First Java Bot����������������������������������������������������������������������������������������������������165
Send Some Text�������������������������������������������������������������������������������������������167
Send a Photo�����������������������������������������������������������������������������������������������169
Bot with Invoice Capabilities�����������������������������������������������������������������������������170
Asking Permission���������������������������������������������������������������������������������������170
Sending an Invoice Message����������������������������������������������������������������������������173

Chapter 9: Week 9: Go����������������������������������������������������������������������181


Installation of Go�����������������������������������������������������������������������������������������������182
Let’s Go�������������������������������������������������������������������������������������������������������������184
Let’s Fib������������������������������������������������������������������������������������������������������������190
First Bot in Go���������������������������������������������������������������������������������������������������193
Just Sending Pictures���������������������������������������������������������������������������������������197

Chapter 10: Week 10: Elixir��������������������������������������������������������������201


Installation��������������������������������������������������������������������������������������������������������202
Using iex������������������������������������������������������������������������������������������������������203
Using mix�����������������������������������������������������������������������������������������������������204
Running iex with mix�����������������������������������������������������������������������������������205

vi
Table of Contents

Project Structure of a mix Project���������������������������������������������������������������������206


config.exs����������������������������������������������������������������������������������������������������207
mix.exs��������������������������������������������������������������������������������������������������������208
Dependencies����������������������������������������������������������������������������������������������209
telegrambox.ex��������������������������������������������������������������������������������������������212
(Back to) Dependencies�������������������������������������������������������������������������������213
Get Something��������������������������������������������������������������������������������������������������216
GetMe����������������������������������������������������������������������������������������������������������216
GetChat��������������������������������������������������������������������������������������������������������217
GetFile���������������������������������������������������������������������������������������������������������218
Using Elixir’s System�����������������������������������������������������������������������������������219
SendPhoto���������������������������������������������������������������������������������������������������220
Telegram Bot�����������������������������������������������������������������������������������������������������221
Bot1: Anything Goes������������������������������������������������������������������������������������221
Bot2: Fibonacci��������������������������������������������������������������������������������������������222

Chapter 11: Week 11: Node.js�����������������������������������������������������������225


Meet RunKit������������������������������������������������������������������������������������������������������226
Creating an Account������������������������������������������������������������������������������������226
First Code on RunKit������������������������������������������������������������������������������������229
A Certain Je Ne Sais Koa�����������������������������������������������������������������������������230
Publishing Some Koa�����������������������������������������������������������������������������������232
Telegram Bot with Webhooks����������������������������������������������������������������������������234
More on the Telegraf Library�����������������������������������������������������������������������������239
Image-to-Chat Example�������������������������������������������������������������������������������239
RegExp, Inline Keyboards, and Embedded Emojis���������������������������������������240

vii
Table of Contents

Running Node.js Locally������������������������������������������������������������������������������������242


Setting Up Node.js���������������������������������������������������������������������������������������243
Using Local Tunnel���������������������������������������������������������������������������������������244

Chapter 12: Week 12: Python�����������������������������������������������������������247


Installation��������������������������������������������������������������������������������������������������������248
A Few Python Programs������������������������������������������������������������������������������������250
Fibonacci 1��������������������������������������������������������������������������������������������������250
Fibonacci 2��������������������������������������������������������������������������������������������������252
Fibonacci 3��������������������������������������������������������������������������������������������������253
Fibonacci 4��������������������������������������������������������������������������������������������������254
Fibonacci 5��������������������������������������������������������������������������������������������������255
First Telegram with Python�������������������������������������������������������������������������������256
First Bot: Send a Random Photo�����������������������������������������������������������������������258
First OpenCV Bot: Changing the Color Space of a Picture���������������������������������260
Second OpenCV Bot: Count Faces���������������������������������������������������������������������262
TensorFlow to Close the Show��������������������������������������������������������������������������265

Index�������������������������������������������������������������������������������������������������271

viii
About the Author
Nicolas Modrzyk has more than 15 years of
IT experience in Asia, Europe, and the United
States and is currently CTO of an international
consulting company in Tokyo, Japan. He is
the author of four other published books,
mostly focused on the Clojure language and
expressive code. When not bringing new
ideas to customers, he spends time with his
two fantastic daughters, Mei and Manon, and
playing live music internationally.

ix
About the Technical Reviewers
Dushyant Rathore is currently working as
a firmware engineer with Western Digital.
His experience includes full-stack web
development, machine learning, decentralized
applications, and others. Dushyant has worked
on several kinds of projects related to IoT,
chatbots, web sites, scrapers, command-
line tools, and machine learning projects,
among others, at various startups. He has participated in national and
international hackathons and has won a few of them. He is a big cloud
computing enthusiast.

Sham Satyaprasad has been a full-stack


software developer for more than four years,
having completed a master’s degree in
embedded systems from Manipal University.
He prides himself on writing highly efficient,
readable, and maintainable code and strongly
believes that coding is an art as much as it is
science. Sham has recently developed a keen
interest in NLP, ML, and data science and has been busy wrapping his
head around these topics.

xi
Acknowledgments
It’s been yet another typing race to get this book out on time and beat the
odds. Divya and Nikhil, thank you so much for teaming up again. I’m really
looking forward to our next collaboration!
I received support from so many people that it would take another
book just to write the list of names. Nevertheless…
Thank you to my sister, Emily, my brother, Gregor, Mum and Dad,
family, cousins, uncles, aunts, friends, Abe-san, Sawada-san, Gucci,
Marshall, Momo, my soulmate Sachiko, soccer friends (I would break a
knee for you), the Irish crew still enjoying Guinness (one more for me!),
the awesome people in America (who always find the LPs I’m missing),
Chris and the Biners, the French team that’s always there to support
me, even without being asked, and the people deep in my heart, for
your never-­ending support. I could not have finished this without you.
I appreciate you all so much.
And, of course, thank you to my two wonderful daughters, Mei and
Manon, for keeping up and always doing your best, even during hard
times. You rock! I love you.

xiii
Introduction
With a hundred ways to do a dozen things, why not try it all?
—Julian Casablancas

Have you ever wondered how you could accomplish more by doing less,
how you could have a sort of double who does all the work while you enjoy
some cool beachside or spend more outdoor time with your beautiful
children? I always have.
I am a big fan of the Telegram chat platform. Let’s call it a platform,
because it is more than a simple chat service with which you can stay in
touch with people who matter to you most. It also enables you to think in
ways you haven’t before.
For example, living in Tokyo, you always care about what time the last
train home is going to depart. I guess most people in big cities around the
globe probably have that same concern. Checking the clock only every so
often can result in a terrible and/or expensive taxi ride, so I started wanting
something that automatically offered me a bunch of options to get home.
The first bot I wrote was to tell me the schedule of the last few trains
home and some different options, from the easiest to reach before the last
few departures to the very latest, which I would have to dash to catch. That
saved me quite a bit of money.
The second bot I wrote was slightly more IoT-oriented. It used a
webcam to send me via Telegram pictures of people who rang my doorbell.
The third one, I also remember, was kind of stupid. It was to use a mini
projector to display the most recent message coming through a Telegram
chat room. (It’s very entertaining to view random messages during a small
party at home.)

xv
Introduction

But there are so many things for which to try to build a bot—search
for a plane ticket, check your fridge, etc. Having a bot is a simple way
to facilitate all the things you do daily, using the same kind of simple
Telegram chat rooms to get answers to questions related to daily life or to
issue commands and conquer the world.
This relatively short book is about learning how to write Telegram
bots in several different programming languages. Why not use one
and stick to it? you might ask. Well, because there’s not one answer to
all questions, and what’s right for others might not be suitable for you.
Exploring different programming languages is also a fun way to examine
the strengths of each language while performing the same tasks. Each of
the Telegram concepts can be introduced one after the other, in a simple
fashion.
Or, you could just jump in and choose the language you want to try and
get started in no time. Some people want it to happen; some wish it would
happen; others make it happen. So, enjoy reading this book, and make it
happen.

xvi
CHAPTER 1

Week 1: Ruby
Mindful Monday Humans, may your coffee kick in before
reality does.
—Napz Cherub Pellazo

Ruby took the world by storm a while ago, owing to the ease and concision
of the code you can write with it. Most programmers have a sweet spot for
Ruby, and when their shell scripts and day-to-day lives get too messy, they
are usually very quick to switch to Ruby.
This first chapter is a bit special, because on top of creating a client
for our bot, I must also introduce you to how to create the bot itself.
Throughout the book, this first bot will be reused at will, although, of
course, the same steps used to make it could be used to create a bot army
and conquer the world!

C
 hatting with the BotFather
To register your own Telegram bot, you must talk to the father of all bots.
This bot father has a name, BotFather; Brad or Vladimir just doesn’t cut it.
He can be reached via Telegram as @BotFather.
BotFather does not sleep and can be reached at any time of day.
BotFather does take showers and always looks fresh. Here is the last profile
picture we have of this handsome bot (Figure 1-1).

© Nicolas Modrzyk 2019 1


N. Modrzyk, Building Telegram Bots, https://doi.org/10.1007/978-1-4842-4197-4_1
Chapter 1 Week 1: Ruby

Figure 1-1. BotFather’s latest profile picture

Finding BotFather is not so difficult; you just have to type his name,
“@BotFather,” in the Telegram list of people in the search box of your
Telegram client (Figure 1-2).

Figure 1-2. Looking for BotFather

2
Chapter 1 Week 1: Ruby

In the preceding list, the name is the one at the bottom. Next, start a
new chat with BotFather by clicking it.
Once the chat is started, you will also be welcomed by our handsome
bot, with a cordial message about APIs, free help, and an invitation to start
the chat (Figure 1-3).

Figure 1-3. Ready?

Once the chat has begun (by pressing the Start button that you can see
at the bottom), you are welcomed by BotFather with a bunch of options on
how to create or edit your list of bots (Figure 1-4).

3
Chapter 1 Week 1: Ruby

Figure 1-4. Say hello to BotFather

4
Chapter 1 Week 1: Ruby

Great! I won’t review the full list of options now but will start just by
creating our new bot. This is done here by typing in the /newbot command
and then following a simple conversation, such as the one in Figure 1-5.

Figure 1-5. Ask BotFather, please, please, for a new bot

Your bot is now ready to use. Can you see in red something like a
secret code? This is the bot token, which is a chain of characters that
will be used to uniquely identify and authenticate your bot against
the Telegram platform. Do not give away this token. Don’t write it in
a book or allow it to hang somewhere on GitHub, especially now that
Microsoft owns it.

5
Chapter 1 Week 1: Ruby

In our case, in the preceding chat, the token that was generated and
given to use is the one following:

624028896:AAFGfIXp3FEPtX1_S2zmHodHRNpu_wD1acA

If your token, like this one, ever becomes compromised, you can use
the /token command with the bot father, to generate a new token, as
shown in the conversation in Figure 1-6.

Figure 1-6. Chat to generate a new token

Alright, the registration of our Telegram bot is all done. So, let’s switch
to a little bit of coding in Ruby.

6
Chapter 1 Week 1: Ruby

S
 etting Up Ruby
Ruby, on most Unix-like platforms, including OS X, is already installed,
or it can be installed using a package manager. For those running lesser
operating systems, like Windows, you can download and install the Ruby
installer (Figure 1-7) from the Ruby download page at www.ruby-lang.
org/en/downloads/. Download the most recent version.

Figure 1-7. Looking for the Windows Ruby installer

After the installation is complete, if you open a terminal (on macOS),


or a command prompt on Windows (Figure 1-8), and can type in the
following commands without getting an error, you are all set:

ruby -v
gem -v

7
Chapter 1 Week 1: Ruby

Figure 1-8. Checking ruby and gem versions

If you have never used Ruby before, you may be wondering what the
gem executable is? It’s simply a Ruby-specific installer for libraries (just like
npm is for Node and pip is for Python), so when you require some open
source library that has been written by someone else, you would use gem to
get it on your machine and the ruby executable to run it.
Apart from Ruby, to have some coding fun outside Notepad, you also
need a text editor, so I propose to use Microsoft’s Visual Studio Code
(https://code.visualstudio.com/), but, of course, any of your favorite
text editors will do.
Alright, let’s get started and code our first bot.

Your First Telegram Bot


To get to talk to our first bot, we will use the Ruby library named
telegram_bot. There are a few other famous libraries that you can find
on RubyGems (https://rubygems.org/), but I find this library to be an
easy one to start and get going with, and I hope you come to agree with
me about this in time.
Actually, you can check for yourself and find your favorite Telegram
library, by querying the RubyGems web site (Figure 1-9).

8
Chapter 1 Week 1: Ruby

Figure 1-9. Looking for gems

To use a library in Ruby, you install it on your machine first, to make it


available to your computer, by using the gem install command, and then
in your Ruby code, you use the *require* function, to make that library
available to your Ruby program.
Let’s create a new folder for this first bot. Change the directory and
then install the Telegram library with gem, as shown following:

mkdir chapter-01
cd chapter-01
gem install telegram_bot

9
Chapter 1 Week 1: Ruby

At the terminal, the output should be something similar to this:

SuperPinkicious:chapter-01 niko$ gem install telegram_bot


Successfully installed telegram_bot-0.0.8
Parsing documentation for telegram_bot-0.0.8
Done installing documentation for telegram_bot after 0 seconds
1 gem installed

The gem is now installed and ready to be used in your code.


Now, you are going to write some code to wake up your bot and make
it come alive. In a new file in that folder, which you can name step0.rb, for
example, let’s write the following lines of Ruby code:

require 'telegram_bot'

bot = TelegramBot.new(token: ENV['BOT_TOKEN'])


bot.get_updates() do |message|
    puts message.to_s
end

What that code does is

• Make the telegram_bot library, installed via gem,


available to your program
• Create a new Ruby bot object, using the Telegram
token exposed via an external variable. This is usually
the recommended way to share your bot code without
giving your bot token to everyone.

• Get the bot instance instantiated, to listen for incoming


messages, using the bot object get_updates() method

• Ensure that, now, whenever a message is sent to the


bot, the bot will print it on the console

10
Chapter 1 Week 1: Ruby

To run the preceding written program on your machine, you pass the
name of the program file, step0.rb, to the ruby executable. Let’s do it.
At the terminal, execute the following command:

ruby  step0.rb

Observe the output (Figure 1-10).

Figure 1-10. Sometimes, it just does not work

Oops! That did not go so well. We forgot to pass the Telegram token to
our program.
This can be done on Linux or OS X with the following:

export BOT_TOKEN='585672177:AAHswpmdA2zP52ZWoJMdteGa0xQ8KeynWvE'

And on Windows with

set BOT_TOKEN=585672177:AAHswpmdA2zP52ZWoJMdteGa0xQ8KeynWvE

Let’s run the program again. This time, it looks like the command
is not finishing… This is expected, as the bot is now actually waiting for
messages.
Let’s be the one to start the conversation, so let’s send a greeting
message.
In the Telegram window, search for the bot and start chatting
(Figure 1-­11).

11
Chapter 1 Week 1: Ruby

Figure 1-11. First message to our bot

By pressing that Start button, the bot is already receiving a message


(Figure 1-12)!

Figure 1-12. First message from our bot!

Hmmm, that was not very readable. With Ruby, you can display a more
legible version of any object, by using the to_yaml function. Let’s update
the code and see what happens.
We call require 'yaml', to import it into the Ruby namespace, and
now we can call the to_yaml on the message the bot has received.

require 'telegram_bot'
require 'yaml'
bot = TelegramBot.new(token: ENV['BOT_TOKEN'])

12
Chapter 1 Week 1: Ruby

bot.get_updates() do |message|
    # puts message.to_s
    puts message.to_yaml
end

You would have to type Ctrl-C to terminate the running version of the
bot first and then start the new bot, by executing the ruby command again.
Figure 1-13 shows the outcome.

Figure 1-13. How are you?

In the console, or in the terminal where the bot was started, you now
can see a more detailed version of the received message.

endSuperPinkicious:chapter-01 niko$ ruby step0.rb


--- !ruby/object:TelegramBot::Message
message_id: 191
from: !ruby/object:TelegramBot::User
  id: 121843071
  first_name: Nico
  last_name: Nico
  username: hellonico
chat: !ruby/object:TelegramBot::Channel
  id: 121843071
  username: hellonico
  title:
date: !ruby/object:DateTime 2018-08-31 07:42:26.000000000 Z
text: how are you?
reply_to_message:

13
Chapter 1 Week 1: Ruby

Actually, whatever the programming language used, this message


format is going to be quite consistent, so it’s a good idea to have a look at
the message fields.

Understanding Received Messages Fields


Table 1-1 briefly explains the fields we have just received via the
Telegram bot.

Table 1-1. Fields Received from the Telegram Bot


Field Sample Value Explanation

message_id 191 The unique identifier


of the bot message
from !ruby/object:TelegramBot::User The user who sent
the message
chat !ruby/object:TelegramBot::Channel The chat/channel
information
date !ruby/object:DateTime 2018-08-­31 When the message
07:42:26.000000000 Z was sent
text how are you? The text of the
message
reply_to_ <empty> The message that
message this message was a
reply to

For standard messages, there is not much beyond what you would
expect from a chat message object. You will probably use the date, text,
and from fields most of the time.

14
Chapter 1 Week 1: Ruby

F irst Reply
Again, Ruby’s concision makes it quite easy to create strings from objects.
With the following, you can use blocks of executable code directly within a
string: #{}.
This makes it very powerful for templated messages, and in our case,
for bot programming. Within the get_updates() call block, let’s now write
and send a reply.

    message.reply do |reply|
        reply.text = "Hello, #{message.from.first_name}!"
        reply.send_with(bot)
end

After restarting the bot (Ctrl-C, ruby step0.rb), we can start a more
talkative version of this Ruby bot (Figure 1-14).

Figure 1-14. Hello, Nico!

That worked pretty smoothly, and I am happy to announce that you


have moved to level 2 of this bot master course.

15
Other documents randomly have
different content
The night of the attack was rainy, but not completely dark, since
the moon was above the horizon during nearly the whole of the
expedition.
The force left Brailoff at one o'clock on the morning of the 26th,
and advanced in two columns up the river, finding great difficulty in
stemming the strong current.
A boat from the Duba Saife, rowing guard some 500 yards in
advance of the squadron, observed the approach of the Russian
boats, but allowed them to pass on their voyage of destruction
without attempting to stop them, or alarm the vessels. On reaching
within 150 yards of the Duba Saife, Dubasoff in the Czarowitch was
challenged, and failing to give the correct answer was immediately
fired at; but, nothing daunted by the hail of shot and bullets, he
dashed on, and succeeded in exploding one of his spar torpedoes on
the port side of the Duba Saife, just under her quarter, a column of
water and débris being thrown up to a height of 120 feet, which
partly filled his boat, but notwithstanding managed to get safely
away. The monitor not sinking as soon as expected, Chestakoff in
the Xénie dashed in, and completed the work of destruction, the
unfortunate ship sinking in a very few minutes after this last
explosion. The Djiquite was struck in the stern, and had to be run
ashore for repairs, but eventually all four boats reached Brailoff in
safety. The Russians allowed to neither killed nor wounded, which,
when the time they were exposed to the fire of the three Turkish
ships (about twenty minutes), the number of men (forty-six)
engaged, and their very close quarters, seems miraculous.
The Duba Saife, thus lost to the Turks, carried two 12 cm. Krupp
guns, and a crew of some sixty officers and men, few of whom were
saved. Lieutenants Dubasoff and Chestakoff were decorated with the
4th Class of the Cross of Saint George, and three seamen received
the insignia of the Order of Military Merit.
This attack was conducted in a most gallant manner, and far more
systematically than the Batoum affair. If instead of holding one of
the boats in reserve, which was part of Dubasoff's plan, and the
remaining three attacking one vessel, the force had divided itself
into two parties, and had made a simultaneous attack on both the
monitors, the probability is that the Fettu Islam would have shared
the fate of her consort.
The officer of the Turkish guard boat was tried by court-martial,
but what his ultimate fate was is not generally known. He certainly
deserved nothing less than death.

3rd Affair.
The Soulina Attack.—The third attempt took place on the 9th-10th
of June, 1877, on a Turkish squadron lying at anchor off Soulina.[T]
This squadron consisted of the three ironclads Feteh Bulend,
Moocardemikhair, and Idglalieh, and a tug, Kartal.
The Russian attacking force consisted of six torpedo boats, viz.
the No. 1, Lieutenant Poutschin; the No. 2, Lieutenant
Rojdestvenski; the Tchesme, Lieutenant Zatzarennyi; the Sinope, the
Navarino, and the Soukoum Kalé. The No. 2 was a specially
constructed torpedo boat, 68 feet long, and very fast. All were
armed with spar torpedoes, with the exception of the Tchesme,
which carried a towing torpedo. The boats were convoyed from
Odessa by the Constantine, some being carried, and some being
towed; another steamer, the Vladimir, supported her. The Turkish
squadron were anchored in quarter line, about one mile from the
harbour; the Kartal, under weigh, being used as an advance guard,
and a few boats rowing guard close to the ships being the only
means of protection adopted by the Turks. Passive obstructions,
such as booms, nets, crinolines, &c., were not thought of, much less
used.
On arriving about five miles from Soulina, the boats were formed
into two groups, the first consisting of the No. 1, the No. 2, and the
Tchesme, and despatched on their way. The working of their engines
was scarcely heard, and all lights were carefully hidden by
tarpaulins.
The first casualty that happened was the disabling of the
Tchesme, by the electric wire of her towing torpedo fouling the
screw, this obliging her to return to the Constantine. Aided by good
fortune, and by the darkness of the night, the No. 1 and the No. 2
succeeded in getting close to (30 yards) one of the Turkish vessels,
the Idglalieh, before being discovered, when they were at once
hailed, and, not answering, a tremendous fire of big guns and rifles
was directed on them from the Idglalieh, which was promptly
followed by that of the whole squadron, though from the other ships
nothing of the boats could be seen.
According to the Russians, the No. 2 succeeded in exploding her
torpedo close to, if not in contact with, a Turkish vessel, but from
eyewitnesses on board the squadron only one explosion was heard,
viz. that of Lieutenant Poutschin's torpedo. Any way, no damage
whatever was experienced by the Ottoman squadron. The No. 1
came down on the Idglalieh's starboard bow, fouled her cable, and
swung alongside, exploding one of her torpedoes in so doing, but
with no other result than a wetting to those of the ironclad's crew,
who were on the forecastle. Alongside Poutschin remained for some
minutes, but at last managed to get clear, and then was either sunk
by the Idglalieh's fire, or, as he avers, on finding his screw foul, he
sunk his boat, rather than let her fall into the hands of the Turks.
Poutschin and four of his crew were picked up, after being some
hours in the water, by the squadron's boats.
The No. 2 seems to have suffered severely, her funnel being bent,
the axle of the steering wheel damaged, sixteen rivets were started,
and the iron keel plate had dropped some 18 inches, and finally the
lower part of her rudder broken, and one of the blades of her screw
bent aft; part of this damage was no doubt the effect of the
explosion of her torpedo, which was probably not in position, but
unless she ran over some loose stones of the Soulina breakwater,
the damage to her keel and rudder cannot be accounted for.
The second group of boats had followed up the first, but on
hearing the noise of the explosions and roar of the guns and rifles
they returned to the Constantine.
That ship, on observing the firing, endeavoured to close the land,
but she grounded, and remained until daylight in a difficult position,
but at last got afloat, and returned to Odessa with five out of her six
torpedo boats.
Lieutenant Rojdestvenski, the Commander of the No. 2, received
the 4th Class of the Cross of Saint George, and three seamen the
insignia of the Order of Military Merit.
On the part of the No. 1 and No. 2, this was a most gallant affair,
though unsuccessful, but as regards the remainder of the boats the
less said the better.
Had the Turkish squadron slipped the instant the alarm was given,
and steamed full speed in the direction of Odessa, the Constantine
and her convoy might have been cut off. Both the Moorcademikhair
and Feteh Bulend were 13 knot ships, and therefore considerably
faster than the enemy. But, as usual, the Turks were far too dilatory
to take advantage of the occasion.

4th Affair.
The Rustchuk Attack.—The fourth torpedo attack was made on
the afternoon of the 20th of June, 1877, on a Turkish monitor off
Rustchuk.
The only Russian torpedo boat sent to the attack on this occasion
was a Thornycroft named the Choutka, commanded by Lieutenant
Skrydloff, and accompanied by a celebrated Russian artist,
Verechtckaguine by name. The instant the torpedo boat was
observed, so well directed and steady a fire was kept up by the
monitor that both the lieutenant and the artist were badly wounded,
and the electric wires of the torpedo severed, thus obliging the
Choutka to beat a retreat. According to the Russian account, the
monitor was struck by the boat's torpedo spar, but the above seems
the more likely version. This was certainly a most audacious attack,
and had the Turks only succeeded in hitting the Choutka with her big
gun, it would have ended fatally for the Russians; as it was, the boat
was struck by several bullets, but none of the crew were wounded.

5th Affair.
The Aluta Attack.—The fifth attack was made on the 30th of June,
1877, on a Turkish monitor off the mouth of the Aluta, in the river
Danube. This attempt, like the last, took place in broad daylight.
Four Russian boats were sent forward, but in spite of the captain of
the Turkish vessel doing all he could to run the boats down, none of
them succeeded in getting sufficiently near the vessel to enable a
torpedo to be placed in contact. The captain of the monitor took the
precaution to rig his lower booms out, and so managed to keep the
enemy's boats at a respectful distance, they imagining that mines
were fixed to the ends of the booms. After two hours of this dodging
about, the Russians, finding the case hopeless, abandoned the
attack.
The Russian account states—1st, that the captain of the monitor
was an Englishman; 2nd, that the vessel was protected by nets and
torpedoes lashed to the extremities of her booms—both of which
statements are radically wrong.
The torpedo boats forming the attack were the Choutka,
Midshipman Niloff, and the Mina, Sub-Lieutenant Arens, both armed
with the spar torpedo.
Unless indeed the Russians acted up to the old proverb which
says "Discretion is the best part of valour," it is difficult to
understand how four small easily handled boats could have been for
one hour endeavouring to strike a ship (which ship was at the same
time being manœuvred with a view of running them down) without
either effecting their object or being sunk or damaged in the
attempt.
The Russians, though unsuccessful, behaved gallantly.
Midshipman Niloff was severely wounded, but no mention is made
as to the number of the crew that were killed and wounded, or of
the damage received by the boats. Niloff received the 4th Class of
the Cross of St. George, and Arens the Order of Military Merit.
The Turkish captain, Ali Bey, behaved most pluckily and skilfully.
The only wonder is that both the boats were not sunk by the
monitor's fire.

6th Affair.
The Soukoum Kaleh Attack.—The sixth attempt was made on the
23rd-24th of August, 1877, on a Turkish ironclad, the Assari Shefket,
at the time lying at anchor off Soukoum Kaleh.[U] Four torpedo boats
composed the attacking force, viz. the Sinope, Lieutenant Pisarefski;
the Torpedoist, Midshipman Nelson Hirst; the Navarino, Lieutenant
Vichnevetski; and the Tchesme, Lieutenant Zatzarennyi, the latter
officer being in command. These boats had been brought to the
entrance of the harbour by the Constantine, and were despatched
on their mission of destruction about half past ten.
An eclipse of the moon occurred on this night, and, taking
advantage of this fact, the four Russian torpedo boats dashed into
the harbour at full speed and made for the Turkish vessel.
Fortunately for the safety of his ship and lives of his crew, the
captain of the Turkish ironclad had several boats rowing guard round
his ship, and otherwise everything on board in readiness for
immediate action. On the attacking flotilla nearing the guard boats,
blue lights were burnt, rifles fired, &c., and the alarm given to those
on the look-out in the Assari Shefket. The moment the enemy were
within range, such a well-directed and heavy fire was poured on
them that the attack was completely foiled. One of the Russian
torpedoes was exploded, but failed to do more than throw a quantity
of water up. The next morning a pole with torpedo fixed on it was
found by the Turks, and on the strength of this and the numerous
fragments of wood similarly found, one if not more of the enemy's
boats it was supposed must have been sunk, or much knocked
about.
This was a much better planned and executed attack, but was
unsuccessful owing to the extreme vigilance of the Turks.
This attempt will always be remembered by the Turks, on account
of the general order that appeared in the papers on the part of the
Russians, in which "the brilliant exploit and successful destruction of
the Turkish ironclad Assari Shefket" was set forth at great length;
she at the time that this appeared being quietly at anchor off the
dockyard at Stamboul, not having received any damage whatever.

7th Affair.
The Second Batoum Attack.—The seventh attempt was made on
the night of the 27th-28th of December, 1877, on several Turkish
men-of-war anchored in the harbour of Batoum (the scene of the
first Russian torpedo attempt and failure). Four boats composed the
attacking force, viz. the Tchesme, Lieutenant Zatzarennyi, in
command, armed with a Whitehead fish torpedo, containing 32
kilog. of gun-cotton, fitted to fire from a tube under the boat's keel;
the Sinope, Lieutenant Stchelinski, armed with a similarly charged
fish torpedo, fitted to fire from a raft, which was towed by the boat,
and two other boats, armed with spar and towing torpedoes.
The means employed at Batoum for the safeguard of the
Ottoman fleet there against such an attack was that of guard boats
and a barrier formed of logs of wood, with planks secured to them,
so arranged by means of weights that the planks remained
perpendicular to the surface of the water when in position.
Owing to the extreme darkness of the night, the Russians
managed to evade the guard boats, and when, as they imagined,
some 60 to 65 yards from a Turkish ironclad, the Tchesme and
Sinope's Whitehead fish torpedoes were started on their deadly
mission; but, owing most probably to the want of practice of
manipulating these somewhat delicate instruments, also to the
darkness, and the slight swell there was on at the time, both missed
their mark, and were landed high and dry on the beach astern of the
ship.
One of these weapons was perfect, the other minus her fore
compartment, this having been knocked off by the torpedo colliding
with some hard object. No explosion was heard or seen by the
Turks.
This was the second time that the fish torpedo had been
employed on actual service, and, as in the previous instance, failed.
The guard boats and barrier of the Turks seem to have been of
little avail.

8th Affair.
The Final Attack.—The eighth and last attempt was made on the
night of the 25th-26th of January, 1878.
This was originally intended to be an attack on the Turkish fleet at
Batoum, but on entering that harbour the two Russian torpedo
boats, the Tchesme, Lieutenant Zatzarennyi, and the Sinope,
Lieutenant Stchelinski, were met by a Turkish revenue steamer,
against which the boats discharged their Whitehead torpedoes,
resulting in her complete destruction, at the same time arousing the
squadron, and causing the boats to beat a retreat.
Though the vessel destroyed was not a frigate, yet the expedition
was successful in so far as proving that it is possible to project
Whitehead fish torpedoes from boats at a distance of 70 to 90 yards
from an enemy's ship, on a dark night, and strike her with them.
This concludes the whole of the offensive torpedo operations that
were carried out during the war, of which two out of eight attempts
were successful, which is without doubt a fair percentage.
There seems every probability that the present struggle between
Chili and Peru, in the Pacific, will afford torpedoists further
experience of the various offensive torpedoes, when subjected to
the test of active service.

FOOTNOTES:
[Q] See page 185.
[R] A Turkish port, situated on the east coast of the Black Sea,
capable of holding several large ships when anchored head and
stern, but otherwise only a few.
[S] A town situated on the south bank of the Danube, about
eight miles from Brailoff.
[T] One of the principal mouths of the Danube.
[U] A place taken from the Russians in the early part of the
war, situated on the east coast of the Black Sea.
CHAPTER VIII.
ON EXPLOSIVES.

E XPLOSION may be defined as the sudden or extremely rapid


conversion of a solid or liquid body of small bulk into gas or
vapour, occupying very many times the volume of the original
substance, and which in addition is highly expanded by the heat
generated during the action.
This sudden or very rapid expansion of volume is attended by an
exhibition of force which is more or less violent, according to the
constitution of the original body and the circumstances of the
explosion.
Any substance capable of undergoing such a change on the
application of heat or other disturbing cause is called an "explosive."
Explosive Force.—Explosive force is directly proportional to the
heat of combustion and the volume of gas, and inversely to the
specific heat of the mixed products.
Explosive effect is directly proportional to the volume of gas
produced and the temperature of the explosion, and inversely as the
time required for the change to take place.
Explosive Effect and Force compared.—Explosive effect depends
upon the rapidity with which the conversion is effected, while the
same amount of explosive force may act suddenly or gradually.
As before stated, explosions are more or less violent according to
the circumstances under which they take place. These may be
considered as follows:—
1.—The physical state of the explosive substance.
2.—The external conditions under which the explosive body is
fired.
3.—The mode of firing.
The Physical State of the Explosive Substance.—Numerous
instances may be cited to show the influence the physical condition
of an explosive body has upon its explosion.
Thus, gunpowder may, by merely varying the size, shape, and
density of the grain, be made to ignite rapidly but burn
comparatively slowly, or be made to ignite more slowly, but once
inflamed to burn very rapidly.
Again, gun-cotton in a loose, uncompressed state, will, if ignited,
only flash off; if it is spun into threads or woven into webs, its rate
of combustion may be so much reduced that it can be used in
gunnery or for a quick fuze; while if powerfully compressed and
damp it burns slowly. Wet gun-cotton requires a primer of dry gun-
cotton and a fulminate fuze to explode; dry, it may be exploded by a
fulminate fuze, &c.
Then nitro-glycerine, when exploded by 15 grains of fulminate of
mercury, and at a temperature above 40° F., is very violently
detonated; below 40° F. it freezes and cannot be similarly exploded.
To obtain the full effect of all explosives, confinement is
absolutely necessary.
The more rapid the explosion the less confinement required,
approaching in the case of some explosives to so small an amount
that it need not, for practical purposes, be considered.
Thus a charge of nitro-glycerine or gun-cotton, when detonated in
the open air, will destroy wrought iron rails, large blocks of stones,
balks of timber, &c.
In the case of the former body, the confinement of the
atmosphere is sufficient.
In the latter, the mechanical cohesion due to compression is
sufficient restraint.
Abel states that if the film of atmosphere surrounding the nitro-
glycerine, not exceeding 1/1000 inch in thickness, be removed, the
explosive effect is much lessened.
A large charge of gunpowder fired in the ordinary way under
water requires a strong case to retain the gases until the action has
become general, or, owing to its slow rate of burning, the case
would be broken before the whole of the charge had been ignited,
and part of the charge drowned.
This is often to be noticed when firing fine-grained powder in
heavy guns.
Igniting the charge at several points diminishes the confinement
needed.
Mode of Firing.—The application of heat, directly or indirectly, is
the principal means of causing an explosion.
The flame from a percussion cap or primer, or a platinum wire
heated to incandescence by an electric current, will directly ignite a
charge. Friction, concussion, &c., will indirectly ignite a charge due
to the conversion of mechanical energy into heat.
It would appear that when one explosive body is used as a means
of firing another, the resultant explosion is due to the blow suddenly
formed by the gas of the firing charge acting percussively upon the
mass to be exploded. If such were the case, then the most powerful
explosive would be the best agent for causing an explosion. But it is
not so.
For example, nitro-glycerine, which is far more powerful than
fulminate of mercury, requires more than 1000 grains to explode
gun-cotton, while only 15 grains of the latter is needful for the same
work, &c.
A small quantity of an explosive substance which is sensitive to
friction or percussion is often used to ignite the original charge.
Detonation.—The instantaneous explosion of the whole mass of a
body is defined as "detonation."
The essential difference between an explosion and a detonation is
the comparative suddenness of the transformation of the solid or
liquid explosive substance into gas and vapour.
Some explosive bodies, such as the fulminates, &c., always
detonate, while the detonation of others depends on the mode of
firing.
Nitro-glycerine always explodes violently, but when fired with an
initiatory charge of fulminate of mercury it is much more powerful
than when fired with gunpowder.
Compressed gun-cotton in the air-dry state can be detonated by 2
grains of fulminate of mercury embedded in the material, but when
it contains 3 per cent. of water over and above the 2 per cent. which
exists normally in the air-dry substance, 15 grains of the fulminate
will not always do so.
Theory of Detonation.—The theory of detonation is not yet
thoroughly understood. That it is not alone due to the heat caused
by the impact of the mechanical energy of the particles of gas, set
free from the initiatory charge on the principal mass, is proved by
the fact of its being possible to detonate wet gun-cotton.
Professor Bloxam terms detonation to be "sympathetic" explosion.
Experiments carried on in England by Professor Abel, and in
France by MM. Champion and Pellet, tend to show that it is due to
the vibratory action of the detonating agent.
Thus a glass may withstand a strong blow, though a particular
note or vibration will smash it.
All explosive compounds and mixtures, including gunpowder, are
susceptible of violent explosion through the agency of a detonation.
Roux and Sarrau.—Roux and Sarrau divide explosions into two
orders:—
1st order.—Detonations.
2nd order.—Simple explosions.
Simple explosions are produced by direct inflammation, or by a
small charge of gunpowder.
Detonations are obtained from nitro-glycerine, gun-cotton, &c., by
exploding with fulminate of mercury.
They state that fulminate of mercury does not detonate
gunpowder; but if the exploding charge is a small amount of nitro-
glycerine, itself detonated by fulminate of mercury, then an
explosion of the first order is obtained.
The relative effects were approximately measured by determining
the quantities necessary to rupture small cast iron shells of supposed
equal strength.
Results of their Experiments.—The following are some of the
results:—

Explosive Effect.
2nd Order. 1st Order.
Gunpowder 1·00 4·34
Gun-cotton 3·00 6·46
Nitro-glycerine 4·80 10·13

According to the above table, nitro-glycerine is more than ten


times, and gun-cotton more than six times, as powerful as
gunpowder fired in the ordinary way (2nd order).
The want of reciprocity between two detonating agents is shown
in a remarkable degree by the following experiments, carried out by
Professor Abel:—
1.—The detonation of 1/4 ounce of gun-cotton (the smallest
quantity that can be thus applied) induced the
simultaneous detonation of nitro-glycerine, enclosed in a
vessel of sheet tin, and placed at a distance of 1 inch
from the gun-cotton.
2.—The detonation of 1/2 ounce of gun-cotton produces the
same effect with an intervening space of 3 inches
between the substances.
3.—The detonation of 2 ounces of nitro-glycerine in close
contact with compressed gun-cotton failed to accomplish
the detonation of the latter, which was simply dispersed
in a fine state of division, in all the instances but one, in
a large number of experiments.
Explosive agents are divided into explosive mixtures and
compounds.
In the former the ingredients are mechanically mixed, and can be
separated by mechanical means.
In the latter the ingredients are chemically combined, and can
only be separated by chemical change.
Torpedo Explosive Agents.—The explosive agents that are
practically the most important, as far as their employment as
torpedo charges are concerned, are as follows:—
Explosive Mixtures.—A.—Explosive mixtures.
1.—Gunpowder.
Nitrate class
2.—Ammonium picrate, or picric powder.
Explosive Compounds.—B.—Explosive compounds.

1.—Nitro-glycerine.
2.—Dynamite (No. 1).
3.—Gun-cotton.
4.—Fulminate of mercury.

A.—Explosive Mixtures.
Gunpowder.—This explosive mixture is composed of seventy-five
parts of nitre (saltpetre), fifteen parts of charcoal, and ten parts of
sulphur.
On being ignited, the oxygen which is feebly held by the nitrogen
combines with the carbon, forming carbonic oxide gas, whilst the
sulphur unites with the potassium of the nitre, the whole
combination being accompanied by a great evolution of heat and
expansion of gas, and the nitrogen is set free.
Properties, &c.—A spark, friction between hard bodies, or a
temperature of 572° F., are any of them sufficient to cause an
explosion of gunpowder.
Slight moisture, due to damp air, &c., produces caking and
deterioration.
Wetting causes permanent destruction.
Frost does not injure it.
It can be fired by ordinary methods.
It can be transported and handled with safety and great ease.
It is not a suitable explosive agent for torpedoes, on account of
its liability to be injured by damp, as well as its not being sufficiently
violent, though for the sake of convenience, &c., it is often employed
for such work.
The effect produced by the explosion of a charge of gunpowder,
ignited by the ordinary method, is that of an uplifting rather than a
shattering effect.
This evil may be greatly remedied, when gunpowder is used as
the charge of a torpedo, by firing it with a detonator, by which
means its fullest explosive effect is developed.
Picric Powder.—The picrates are salts of picric acid.
Picric acid is formed by the action of nitric acid on carbolic acid.
The picrate employed by Professor Abel is prepared from picric
acid and ammonium. This preparation, or salt mixed with nitre
(saltpetre), forms Abel's picric powder.
Properties, &c.—It is prepared for use in a similar manner to
gunpowder, and it can be handled in the same way.
It is less violent than dynamite or gun-cotton, though much more
so than gunpowder.
It is difficult to explode it by blows or friction.
If flame be applied to it, the part touched burns, but the
combustion does not become general.
This explosive agent will probably be used for spar torpedoes,
when gun-cotton or dynamite are not employed.

B.—Explosive Compounds.
Nitro-glycerine.—Nitro-glycerine is formed by the action of nitric
acid upon glycerine at a low temperature.
The manufacture of this compound consists, first, in the slow
mixture of the glycerine with the acid, at a low temperature;
secondly, in washing the nitro-glycerine from the excess of acid with
water.
The nitric acid before use is mixed with a certain proportion of
strong sulphuric acid, so that the water formed during the reaction
may be taken up, and thus any dilution of the nitric acid is
prevented.
Nitro-glycerine is composed of carbon, hydrogen, nitrogen, and
oxygen, as indicated by the equation C3H5N3O9.

Properties, &c.—At ordinary temperatures nitro-glycerine is an oily


liquid, having a specific gravity of 1·6. Freshly made it is creamy
white and opaque, but clears and becomes colourless on standing
for a certain time, depending on the temperature.
It does not mix with, nor is it affected by, water. It has a sweet,
aromatic taste, and produces a violent headache if placed upon the
tongue.
The opaque, freshly made nitro-glycerine does not freeze until the
temperature is lowered to 3°-5° below zero, F., but, when cleared, it
freezes at 39°-40° F. Nitro-glycerine freezes to a white crystalline
mass, and in this state it can be thawed by placing the vessel
containing it in water, at a temperature not over 100° F.
If flame is applied to freely exposed nitro-glycerine, it burns
slowly without explosion.
Nitro-glycerine in a state of decomposition becomes very
sensitive, exploding violently when struck, even when unconfined.
Pure nitro-glycerine does not spontaneously decompose at any
ordinary temperature, but if it contains any free acid, then
decomposition may happen. When pure, it is not sensitive to friction,
or moderate percussion. If struck with a hammer, only the particle
receiving the blow explodes, the remainder being scattered.
The firing point of nitro-glycerine is about 356° F., though it
begins to decompose at a lower temperature.
The mode of firing nitro-glycerine usually employed is that of a
fulminate of mercury detonating fuse.
Nitro-glycerine in the frozen state cannot be fired even by large
charges of fulminate.
In one instance, 1600 lbs. of liquid nitro-glycerine exploded in a
magazine containing 600 lbs. of the same substance in a frozen
state, but failed to fire the latter, only breaking it up and scattering it
in every direction.
Dynamite.—This explosive compound is merely a preparation in
which nitro-glycerine is itself presented for use, its explosive
properties being those of the nitro-glycerine contained in it, as the
absorbent is an inert body.
Dynamite is formed of seventy-five parts of nitro-glycerine
absorbed by twenty-five parts of a porous siliceous earth or
"kieselguhr."
The best substitute for "kieselguhr" is ashes of bog-head coal.
Dynamite is a loose, soft, readily moulded substance, of a buff
colour.
The preparation of dynamite is very simple.
The nitro-glycerine is mixed by means of wooden spatulas with
the fine white powder (kieselguhr) in a leaden vessel.
It freezes at 39°-40° F., and when solidly frozen cannot be
exploded, but if in a pulverised state it can be exploded, though with
diminished violence.
It can be easily thawed, by placing the vessel containing it in hot
water.
Friction or moderate percussion does not explode it.
Its firing point is 356° F.
If flame be applied to it, it burns with a strong flame.
It is fired by means of fulminate of mercury, and its explosive
force is about seven times that of gunpowder.
For ground and buoyant mines, where actual contact between the
hostile vessel and the torpedo will be rarely achieved, this being next
to nitro-glycerine the most violent of all known explosive agents, and
being cheaply and readily procured, is the very best explosive for
such torpedoes.
That it is not generally adopted is owing to its containing a large
proportion of that seemingly dangerous substance, nitro-glycerine,
which makes the handling of dynamite a somewhat hazardous
operation.
According to Professor Abel, there are now as many as fifteen
dynamite factories in different parts of the world (including a very
extensive one in Scotland) working under the supervision of Mr.
Nobel, the originator of the nitro-glycerine industry; and six or seven
other establishments exist where dynamite or preparations of very
similar character are also manufactured.
The total production of dynamite in 1867 was only eleven tons,
while in 1878 it amounted to 6140 tons.
This explosive compound is most extensively used for general
blasting purposes all over the world, and for this purpose, owing to
its cheapness and the convenience in manipulating it, is far superior
to compressed gun-cotton.
Gun-cotton is formed by the action of concentrated nitric acid on
cotton, its composition being indicated by the formula CH7(NO2)3O5.

Professor Abel's process for manufacturing pulped and


compressed gun-cotton is as follows:—
Cotton waste is the form of cotton used; it is picked and cleaned,
thoroughly dried at 160° F., and then allowed to cool.
The strongest nitric and sulphuric acids are employed, mixed in
the proportion of one part of the former to three of the latter by
weight. These are mixed in large quantities, and stored in cast-iron
tanks.
The cotton in 1-lb. charges is immersed in the acid mixture, which
is contained in a trough surrounded by cold water. After being
subjected to the action of the acid for a short space of time, the
cotton is taken up, placed upon a perforated shelf, and as much as
possible of the acid squeezed out of it. It is then put into jars,
covered with fresh acid, and the jars placed in fresh water,
remaining there for twenty-four hours.
To remove the acid, the gun-cotton from the jars is thrown into a
centrifugal strainer, by which nearly all the acid is expelled. It is then
diffused quickly in small quantities through a large volume of water,
and again passed through a centrifugal machine.
The next process is that of thoroughly washing the gun-cotton,
for the purpose of removing the traces of the acid still adhering to it.
By pulping, which operation is performed in pulping engines or
beaters, the washing is expeditious and thorough.
A beater is an oblong tub in which is placed a revolving wheel
carrying strips of steel on its circumference. From the bottom under
the wheel project similar steel strips.
The action of this machine is as follows:—
By the rotation of the wheel, the gun-cotton which is suspended
in water circulates around the tub, and is drawn between the two
sets of steel projections, by which it is reduced to a state of pulp.
The bottom of the tub is movable, and thus the space through
which the gun-cotton must pass may be contracted, as the operation
proceeds.
The pulping being complete, the contents are run into poachers
for the final washing.
A poacher is a large oblong wooden tub. On one side at the
middle is placed a wooden paddle-wheel, which extends half way
across the tub.
In the poacher the pulped gun-cotton is stirred for a long time
with a large quantity of water. The revolution of the paddle-wheel
keeps up a constant circulation, and care is taken that no deposit
occurs in any part of the tub.
Having converted the cotton into gun-cotton, reduced it to a state
of pulp, and thoroughly washed it, the next process is to separate
the water from the pulp, and compress it into cakes or discs.
This is accomplished by means of two presses, the first of which
has 36 hollow cylinders, in which perforated plungers work upwards.
These plungers having been drawn down, the cylinders are filled
with the water-laden pulp, and their tops covered with a weight; the
plungers are then forced up by hydraulic power, compressing the
pulp, and forcing the water to escape through their perforations.
The second one is used to more solidly compress the cylindrical
masses of gun-cotton formed by the action of the first press, a
pressure of 6 tons to the inch being in this case applied.
About 6 per cent. of moisture still remains in the discs, which can
be readily removed by drying.
Properties.—Cotton converted into gun-cotton is little changed in
appearance, though the latter is harsher to the touch than the
former.
If a flame be applied to dry loose gun-cotton, it flashes up,
without explosion; if compressed it burns rapidly, but quietly.
Moist compressed gun-cotton under the same circumstances
burns away slowly.
Gun-cotton containing 12 to 14 per cent. of water is ignited with
much difficulty on applying a highly heated body. As it leaves the
hydraulic press upon being converted from the pulped state to
masses, it contains about 15 per cent. of water; in this condition it
may be thrown on to a fire or held in a flame without exhibiting any
tendency to burn; the masses may be perforated by means of a red-
hot iron, or with a drilling tool, and they may with perfect safety be
cut into slices by means of saws revolving with great rapidity. If
placed upon a fire and allowed to remain there, a feeble and
transparent flame flickers over the surface of the wet gun-cotton
from time to time as the exterior becomes sufficiently dry to inflame;
in this way a piece of compressed gun-cotton will burn away very
gradually indeed.
To test the safety of wet gun-cotton, the following two
experiments among many have been made:—
Quantities of wet gun-cotton, 20 cwt. each, packed in one
instance in a large, strong wooden case, and in the other in a
number of strong packing cases, were placed in small magazines,
very substantially built of concrete and brickwork. Large fires were
kindled around the packages in each building, the doors being just
left ajar. The entire contents of both buildings had burned away,
without anything approaching explosive action, in less than two
hours.
This comparatively great safety of wet gun-cotton, coupled with
the fact that its detonation in that state may be readily accomplished
through the agency of a small quantity of dry gun-cotton, termed a
"primer," which, by means of a fulminating fuze, or detonator, is
made to act as the initiative detonating agent, gives it important
advantages over other violent explosive agents, when used for
purposes which involve the employment of a considerable quantity
of the material, on account of the safety attending its storage and
necessary manipulation.
From experiments conducted by engineer officers in Austria, it
was found that if boxes containing dry compressed gun-cotton are
fired into from small arms, even at a short range, the gun-cotton is
generally inflamed, but never exploded, the sharpness of the blow
essential to effect an explosion, which the bullet might otherwise
give, being diminished by its penetration through the side of the box
before reaching the explosive. Wet gun-cotton, containing even as
little as 15 per cent. of water, is never inflamed on these conditions.
Dynamite, on the other hand, is invariably detonated when struck
by a bullet on passing through the side of the box.
Gun-cotton is insoluble in and unaffected by water.
The firing point of gun-cotton is about 360° F.
The temperature of explosion of gun-cotton is about 8700° F.,
being more than double that of gunpowder. Gun-cotton is not
sensitive to friction or percussion.
If not perfectly converted or thoroughly washed, gun-cotton is
liable to spontaneous decomposition, which under favourable
conditions may result in explosion.
Compressed gun-cotton is free from such danger, as it may be
kept and used saturated with water. It is stored in the wet state,
care being taken that it is not exposed to a temperature that will
freeze the water in the cakes, as if this occurs they are liable to be
disintegrated by the expansion of the water in freezing.
Gun-cotton is the agent most extensively used for all kinds of
military engineering and submarine operations in Great Britain, it
being especially manufactured by the English government for that
express purpose; but in other countries it is not so manufactured,
and therefore, as it is little used for other than military purposes, it is
not to any extent privately manufactured, as is the case with other
explosives, such as dynamite, dualine, lithofracteur, &c., and thus, in
case of war, would be somewhat difficult to obtain out of England.
Compared with dynamite, it is not so violent, and occupies more
space, weight for weight, and also requires a more complicated
means of detonating it. On the other hand, gun-cotton is infinitely
safer to store and manipulate, and is not so subject to detonation by
concussion (not being so sensitive) as dynamite.
Fulminate of Mercury.—Fulminate of mercury is formed by the
action of mercuric nitrate and nitric acid upon alcohol. The mode of
preparation is as follows:—
Dissolve one part of mercury in twelve parts of nitric acid, and
pour this solution into twelve parts of alcohol.
Pour this mixture into a vessel which is placed in hot water until it
darkens and becomes turbid and begins to evolve dense white
fumes, then remove it from the water. The reaction goes on, with
strong effervescence and copious evolution of dense white ethereal
vapours. If red fumes appear, cold alcohol should be added to check
the violence of the action.
The operation should be performed at a distance from a fire or
flame, and in a strong draught, so that the vapours may be carried
off.
When the liquid clears, and the dense white fumes are no longer
given off, further action is stopped by filling up with cold water. The
fulminate settles to the bottom of the vessel as a grey crystalline
precipitate. The liquid is then poured off, and the fulminate washed
several times by decantation or upon a filter.
Dry fulminate of mercury explodes violently when heated to 367°
F., when forcibly struck by the electric spark, &c.
When wet it is inexplosive, and therefore it is always kept wet,
being dried in small amounts when required for use.
Fulminate of mercury is applied in many ways, either pure or
mixed with other substances, as in percussion caps, percussion
powder, primers, detonators, &c.
For the purpose of detonating nitro-glycerine or its preparations,
15 grains of the fulminate are sufficient, but to detonate gun-cotton
25 grains are necessary. The fulminate in detonating fuzes should be
enclosed in a copper case or cap, and must never be loose. The
fulminate should be wet when charging the detonators, as it is very
dangerous to handle when dry.
Great care is requisite in handling this explosive compound.
In addition to the foregoing explosive compounds and mixtures,
the following explosive agents have also been employed for the
purposes of submarine operations, though only to a small extent.
Dualin.—Dualin is a nitro-glycerine preparation formed by mixing
sawdust and saltpetre with that substance.
This preparation, inferior to dynamite, was employed by the
Germans as the explosive agent for their submarine mines during
the Franco-German war (1870-71).
Lithofracteur.—Lithofracteur is also a preparation of nitro-
glycerine. It is composed of the following materials:—Nitro-glycerine,
kieselguhr, coal, soda, saltpetre, and sulphur.
This explosive agent, also inferior to dynamite, is used, though
not very extensively, by the French for their submarine mines.
Horsley's Powder.—Horsley's powder is a chlorate mixture formed
of potassium, chlorate, and galls. This explosive mixture was
formerly used by Captain Harvey for his towing torpedo, but has
recently been discarded for compressed gun-cotton.
Abel's Detonation Experiments.—The following are the results of
experiments carried out by Professor Abel, C.B., F.R.S., on the
subject of detonation:—
1.—A fuze containing rather more than 1 ounce of gunpowder,
strongly confined, exploded in contact with a mass of
compressed gun-cotton, only inflames it, although the
explosion of the fuze is apparently a sharp one.
2.—45 grains of fulminate of mercury, exploded unconfined on
the surface of a piece of compressed gun-cotton, only
inflames or disperses it.
3.—A fuze containing 9 grains of fulminate of mercury, strongly
confined, exploded in contact with compressed gun-
cotton, or dynamite, detonates it with certainty.
4.—An equal quantity of fulminate of mercury, similarly
confined, does not detonate uncompressed gun-cotton in
which it is imbedded, but merely disperses and inflames
it.
5.—150 grains of compressed gun-cotton, detonated in
proximity to dynamite, detonates the latter.
6.—3 ounces of dynamite, and very much larger quantities,
detonated in contact with compressed gun-cotton, only
disperses it.
7.—A wrought-iron rail can be destroyed by detonating 8 ounces
of compressed gun-cotton placed unconfined on the rail.
8.—A piece of wet gun-cotton, quite uninflammable, removed
from a fire, and detonated upon a block of granite, using
a small primer of dry gun-cotton, shatters the block.
9.—A submerged charge of wet gun-cotton, open on all sides to
the water, and merely confined around the dry initiative,
or primer, by means of a net, can be exploded.
Explosive Agents in Torpedoes.—The explosive agents that at the
present time are most generally used in torpedoes are gunpowder,
gun-cotton in the wet compressed state, and dynamite, and these
may be compared as to their properties and their explosive effects.
Gunpowder.—Gunpowder is a familiar material, in general use for
all military purposes. It can be handled and transported with safety
and ease, and it can be fired by ordinary methods. But for
submarine purposes it has the disadvantage of being very easily
injured by water, so that it is absolutely necessary to enclose it in
water-tight cases.
Gun-cotton.—Gun-cotton is free from liability to accidents, and in
this matter, and the safety of its manufacture, it compares
favourably with gunpowder.
It is peculiarly adapted to submarine work, being unaffected by
water. And as it may be kept in water, ready for use, it can be safely
carried on board ship in large quantities. It is far more violent in its
action when detonated than gunpowder. The chief objection to its
use is, that being applied only for special purposes, it is not readily
obtained. Also it requires a peculiar and somewhat complicated
mode of firing it.
Dynamite.—Dynamite is more easily manufactured than the two
foregoing explosives. The fact of it containing nitro-glycerine, which
has a bad reputation, has militated against its use as a torpedo
explosive agent, though for blasting purposes it is most extensively
used. Though not directly affected by water, its firing is hindered
when diffused through water. Another disadvantage is its high
freezing point. Like gun-cotton, it requires special means to fire it,
though much simpler, and also is much more powerful than
gunpowder. The explosive effect of dynamite or gun-cotton is a
rending or a shattering one, while that of gunpowder is an uplifting
or heaving one.
Again, it is necessary when using gunpowder that the object be in
the line of least resistance, but with dynamite or gun-cotton the
effect is nearly equal in every direction, therefore for submarine
operations, either dynamite or gun-cotton is the explosive agent that
should be invariably used.
Size of Torpedo Charges.—For permanent mines, a charge of 700
lbs. to 1000 lbs. of gun-cotton is quite sufficient, though too large a
charge cannot be employed, except as regards the matter of
convenience.
For buoyant mines, 500 lbs. to 700 lbs. of gun-cotton is an ample
charge, and for contact mines, 200 lbs. to 300 lbs. of gun-cotton is
sufficient. In spar torpedoes, where lightness is a consideration,
gun-cotton charges of 30 lbs. to 50 lbs. will be found ample, and
similarly in the case of the towing or locomotive torpedoes. Of
course, with regard to such a submarine weapon as the Lay torpedo
boat, any size charge may be carried, according to the wish of the
builder.
Torpedo Explosions illustrated.—At Fig. 166 is represented a
sketch of a torpedo explosion, from a photograph taken at the
moment the column of water was at its greatest elevation. The
torpedo contained 432 lbs. of gun-cotton, and was exploded under
27 feet of water.
The height of the column thrown up measured 81 feet, and the
diameter at the base 132 feet.
SUBMARINE MINE EXPLOSION.
SUBMARINE MINE EXPLOSIONS.

At Fig. 165 is shown a sketch of two submarine mine explosions


from an instantaneous photograph; the schooner which is shown in
the sketch happened to be passing at the moment of explosion, thus
affording a comparison as to the size of the columns of water thrown
up.
The column on the left was due to the explosion of a submarine
mine containing 100 lbs. gunpowder at a depth of 10 feet below the
surface. That on the right was the result of an explosion of a similar
mine, but at a depth of 41 feet below the surface. Its extreme height
was 400 feet.
Welcome to our website – the ideal destination for book lovers and
knowledge seekers. With a mission to inspire endlessly, we offer a
vast collection of books, ranging from classic literary works to
specialized publications, self-development books, and children's
literature. Each book is a new journey of discovery, expanding
knowledge and enriching the soul of the reade

Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.

Let us accompany you on the journey of exploring knowledge and


personal growth!

textbookfull.com

You might also like